clang  15.0.0git
SemaDecl.cpp
Go to the documentation of this file.
1 //===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements semantic analysis for declarations.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTConsumer.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/ASTLambda.h"
18 #include "clang/AST/CharUnits.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/StmtCXX.h"
28 #include "clang/Basic/Builtins.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "clang/Lex/HeaderSearch.h" // TODO: Sema shouldn't depend on Lex
33 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
34 #include "clang/Lex/ModuleLoader.h" // TODO: Sema shouldn't depend on Lex
35 #include "clang/Lex/Preprocessor.h" // Included for isCodeCompletionEnabled()
37 #include "clang/Sema/DeclSpec.h"
40 #include "clang/Sema/Lookup.h"
42 #include "clang/Sema/Scope.h"
43 #include "clang/Sema/ScopeInfo.h"
45 #include "clang/Sema/Template.h"
46 #include "llvm/ADT/SmallString.h"
47 #include "llvm/ADT/Triple.h"
48 #include <algorithm>
49 #include <cstring>
50 #include <functional>
51 #include <unordered_map>
52 
53 using namespace clang;
54 using namespace sema;
55 
57  if (OwnedType) {
58  Decl *Group[2] = { OwnedType, Ptr };
59  return DeclGroupPtrTy::make(DeclGroupRef::Create(Context, Group, 2));
60  }
61 
62  return DeclGroupPtrTy::make(DeclGroupRef(Ptr));
63 }
64 
65 namespace {
66 
67 class TypeNameValidatorCCC final : public CorrectionCandidateCallback {
68  public:
69  TypeNameValidatorCCC(bool AllowInvalid, bool WantClass = false,
70  bool AllowTemplates = false,
71  bool AllowNonTemplates = true)
72  : AllowInvalidDecl(AllowInvalid), WantClassName(WantClass),
73  AllowTemplates(AllowTemplates), AllowNonTemplates(AllowNonTemplates) {
74  WantExpressionKeywords = false;
75  WantCXXNamedCasts = false;
76  WantRemainingKeywords = false;
77  }
78 
79  bool ValidateCandidate(const TypoCorrection &candidate) override {
80  if (NamedDecl *ND = candidate.getCorrectionDecl()) {
81  if (!AllowInvalidDecl && ND->isInvalidDecl())
82  return false;
83 
84  if (getAsTypeTemplateDecl(ND))
85  return AllowTemplates;
86 
87  bool IsType = isa<TypeDecl>(ND) || isa<ObjCInterfaceDecl>(ND);
88  if (!IsType)
89  return false;
90 
91  if (AllowNonTemplates)
92  return true;
93 
94  // An injected-class-name of a class template (specialization) is valid
95  // as a template or as a non-template.
96  if (AllowTemplates) {
97  auto *RD = dyn_cast<CXXRecordDecl>(ND);
98  if (!RD || !RD->isInjectedClassName())
99  return false;
100  RD = cast<CXXRecordDecl>(RD->getDeclContext());
101  return RD->getDescribedClassTemplate() ||
102  isa<ClassTemplateSpecializationDecl>(RD);
103  }
104 
105  return false;
106  }
107 
108  return !WantClassName && candidate.isKeyword();
109  }
110 
111  std::unique_ptr<CorrectionCandidateCallback> clone() override {
112  return std::make_unique<TypeNameValidatorCCC>(*this);
113  }
114 
115  private:
116  bool AllowInvalidDecl;
117  bool WantClassName;
118  bool AllowTemplates;
119  bool AllowNonTemplates;
120 };
121 
122 } // end anonymous namespace
123 
124 /// Determine whether the token kind starts a simple-type-specifier.
126  switch (Kind) {
127  // FIXME: Take into account the current language when deciding whether a
128  // token kind is a valid type specifier
129  case tok::kw_short:
130  case tok::kw_long:
131  case tok::kw___int64:
132  case tok::kw___int128:
133  case tok::kw_signed:
134  case tok::kw_unsigned:
135  case tok::kw_void:
136  case tok::kw_char:
137  case tok::kw_int:
138  case tok::kw_half:
139  case tok::kw_float:
140  case tok::kw_double:
141  case tok::kw___bf16:
142  case tok::kw__Float16:
143  case tok::kw___float128:
144  case tok::kw___ibm128:
145  case tok::kw_wchar_t:
146  case tok::kw_bool:
147  case tok::kw___underlying_type:
148  case tok::kw___auto_type:
149  return true;
150 
151  case tok::annot_typename:
152  case tok::kw_char16_t:
153  case tok::kw_char32_t:
154  case tok::kw_typeof:
155  case tok::annot_decltype:
156  case tok::kw_decltype:
157  return getLangOpts().CPlusPlus;
158 
159  case tok::kw_char8_t:
160  return getLangOpts().Char8;
161 
162  default:
163  break;
164  }
165 
166  return false;
167 }
168 
169 namespace {
170 enum class UnqualifiedTypeNameLookupResult {
171  NotFound,
172  FoundNonType,
173  FoundType
174 };
175 } // end anonymous namespace
176 
177 /// Tries to perform unqualified lookup of the type decls in bases for
178 /// dependent class.
179 /// \return \a NotFound if no any decls is found, \a FoundNotType if found not a
180 /// type decl, \a FoundType if only type decls are found.
181 static UnqualifiedTypeNameLookupResult
183  SourceLocation NameLoc,
184  const CXXRecordDecl *RD) {
185  if (!RD->hasDefinition())
186  return UnqualifiedTypeNameLookupResult::NotFound;
187  // Look for type decls in base classes.
188  UnqualifiedTypeNameLookupResult FoundTypeDecl =
189  UnqualifiedTypeNameLookupResult::NotFound;
190  for (const auto &Base : RD->bases()) {
191  const CXXRecordDecl *BaseRD = nullptr;
192  if (auto *BaseTT = Base.getType()->getAs<TagType>())
193  BaseRD = BaseTT->getAsCXXRecordDecl();
194  else if (auto *TST = Base.getType()->getAs<TemplateSpecializationType>()) {
195  // Look for type decls in dependent base classes that have known primary
196  // templates.
197  if (!TST || !TST->isDependentType())
198  continue;
199  auto *TD = TST->getTemplateName().getAsTemplateDecl();
200  if (!TD)
201  continue;
202  if (auto *BasePrimaryTemplate =
203  dyn_cast_or_null<CXXRecordDecl>(TD->getTemplatedDecl())) {
204  if (BasePrimaryTemplate->getCanonicalDecl() != RD->getCanonicalDecl())
205  BaseRD = BasePrimaryTemplate;
206  else if (auto *CTD = dyn_cast<ClassTemplateDecl>(TD)) {
208  CTD->findPartialSpecialization(Base.getType()))
209  if (PS->getCanonicalDecl() != RD->getCanonicalDecl())
210  BaseRD = PS;
211  }
212  }
213  }
214  if (BaseRD) {
215  for (NamedDecl *ND : BaseRD->lookup(&II)) {
216  if (!isa<TypeDecl>(ND))
217  return UnqualifiedTypeNameLookupResult::FoundNonType;
218  FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
219  }
220  if (FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound) {
221  switch (lookupUnqualifiedTypeNameInBase(S, II, NameLoc, BaseRD)) {
222  case UnqualifiedTypeNameLookupResult::FoundNonType:
223  return UnqualifiedTypeNameLookupResult::FoundNonType;
224  case UnqualifiedTypeNameLookupResult::FoundType:
225  FoundTypeDecl = UnqualifiedTypeNameLookupResult::FoundType;
226  break;
227  case UnqualifiedTypeNameLookupResult::NotFound:
228  break;
229  }
230  }
231  }
232  }
233 
234  return FoundTypeDecl;
235 }
236 
238  const IdentifierInfo &II,
239  SourceLocation NameLoc) {
240  // Lookup in the parent class template context, if any.
241  const CXXRecordDecl *RD = nullptr;
242  UnqualifiedTypeNameLookupResult FoundTypeDecl =
243  UnqualifiedTypeNameLookupResult::NotFound;
244  for (DeclContext *DC = S.CurContext;
245  DC && FoundTypeDecl == UnqualifiedTypeNameLookupResult::NotFound;
246  DC = DC->getParent()) {
247  // Look for type decls in dependent base classes that have known primary
248  // templates.
249  RD = dyn_cast<CXXRecordDecl>(DC);
250  if (RD && RD->getDescribedClassTemplate())
251  FoundTypeDecl = lookupUnqualifiedTypeNameInBase(S, II, NameLoc, RD);
252  }
253  if (FoundTypeDecl != UnqualifiedTypeNameLookupResult::FoundType)
254  return nullptr;
255 
256  // We found some types in dependent base classes. Recover as if the user
257  // wrote 'typename MyClass::II' instead of 'II'. We'll fully resolve the
258  // lookup during template instantiation.
259  S.Diag(NameLoc, diag::ext_found_in_dependent_base) << &II;
260 
261  ASTContext &Context = S.Context;
262  auto *NNS = NestedNameSpecifier::Create(Context, nullptr, false,
263  cast<Type>(Context.getRecordType(RD)));
264  QualType T = Context.getDependentNameType(ETK_Typename, NNS, &II);
265 
266  CXXScopeSpec SS;
267  SS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
268 
269  TypeLocBuilder Builder;
270  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
271  DepTL.setNameLoc(NameLoc);
273  DepTL.setQualifierLoc(SS.getWithLocInContext(Context));
274  return S.CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
275 }
276 
277 /// If the identifier refers to a type name within this scope,
278 /// return the declaration of that type.
279 ///
280 /// This routine performs ordinary name lookup of the identifier II
281 /// within the given scope, with optional C++ scope specifier SS, to
282 /// determine whether the name refers to a type. If so, returns an
283 /// opaque pointer (actually a QualType) corresponding to that
284 /// type. Otherwise, returns NULL.
286  Scope *S, CXXScopeSpec *SS,
287  bool isClassName, bool HasTrailingDot,
288  ParsedType ObjectTypePtr,
289  bool IsCtorOrDtorName,
290  bool WantNontrivialTypeSourceInfo,
291  bool IsClassTemplateDeductionContext,
292  IdentifierInfo **CorrectedII) {
293  // FIXME: Consider allowing this outside C++1z mode as an extension.
294  bool AllowDeducedTemplate = IsClassTemplateDeductionContext &&
295  getLangOpts().CPlusPlus17 && !IsCtorOrDtorName &&
296  !isClassName && !HasTrailingDot;
297 
298  // Determine where we will perform name lookup.
299  DeclContext *LookupCtx = nullptr;
300  if (ObjectTypePtr) {
301  QualType ObjectType = ObjectTypePtr.get();
302  if (ObjectType->isRecordType())
303  LookupCtx = computeDeclContext(ObjectType);
304  } else if (SS && SS->isNotEmpty()) {
305  LookupCtx = computeDeclContext(*SS, false);
306 
307  if (!LookupCtx) {
308  if (isDependentScopeSpecifier(*SS)) {
309  // C++ [temp.res]p3:
310  // A qualified-id that refers to a type and in which the
311  // nested-name-specifier depends on a template-parameter (14.6.2)
312  // shall be prefixed by the keyword typename to indicate that the
313  // qualified-id denotes a type, forming an
314  // elaborated-type-specifier (7.1.5.3).
315  //
316  // We therefore do not perform any name lookup if the result would
317  // refer to a member of an unknown specialization.
318  if (!isClassName && !IsCtorOrDtorName)
319  return nullptr;
320 
321  // We know from the grammar that this name refers to a type,
322  // so build a dependent node to describe the type.
323  if (WantNontrivialTypeSourceInfo)
324  return ActOnTypenameType(S, SourceLocation(), *SS, II, NameLoc).get();
325 
326  NestedNameSpecifierLoc QualifierLoc = SS->getWithLocInContext(Context);
327  QualType T = CheckTypenameType(ETK_None, SourceLocation(), QualifierLoc,
328  II, NameLoc);
329  return ParsedType::make(T);
330  }
331 
332  return nullptr;
333  }
334 
335  if (!LookupCtx->isDependentContext() &&
336  RequireCompleteDeclContext(*SS, LookupCtx))
337  return nullptr;
338  }
339 
340  // FIXME: LookupNestedNameSpecifierName isn't the right kind of
341  // lookup for class-names.
342  LookupNameKind Kind = isClassName ? LookupNestedNameSpecifierName :
343  LookupOrdinaryName;
344  LookupResult Result(*this, &II, NameLoc, Kind);
345  if (LookupCtx) {
346  // Perform "qualified" name lookup into the declaration context we
347  // computed, which is either the type of the base of a member access
348  // expression or the declaration context associated with a prior
349  // nested-name-specifier.
350  LookupQualifiedName(Result, LookupCtx);
351 
352  if (ObjectTypePtr && Result.empty()) {
353  // C++ [basic.lookup.classref]p3:
354  // If the unqualified-id is ~type-name, the type-name is looked up
355  // in the context of the entire postfix-expression. If the type T of
356  // the object expression is of a class type C, the type-name is also
357  // looked up in the scope of class C. At least one of the lookups shall
358  // find a name that refers to (possibly cv-qualified) T.
359  LookupName(Result, S);
360  }
361  } else {
362  // Perform unqualified name lookup.
363  LookupName(Result, S);
364 
365  // For unqualified lookup in a class template in MSVC mode, look into
366  // dependent base classes where the primary class template is known.
367  if (Result.empty() && getLangOpts().MSVCCompat && (!SS || SS->isEmpty())) {
368  if (ParsedType TypeInBase =
369  recoverFromTypeInKnownDependentBase(*this, II, NameLoc))
370  return TypeInBase;
371  }
372  }
373 
374  NamedDecl *IIDecl = nullptr;
375  UsingShadowDecl *FoundUsingShadow = nullptr;
376  switch (Result.getResultKind()) {
379  if (CorrectedII) {
380  TypeNameValidatorCCC CCC(/*AllowInvalid=*/true, isClassName,
381  AllowDeducedTemplate);
382  TypoCorrection Correction = CorrectTypo(Result.getLookupNameInfo(), Kind,
383  S, SS, CCC, CTK_ErrorRecovery);
384  IdentifierInfo *NewII = Correction.getCorrectionAsIdentifierInfo();
385  TemplateTy Template;
386  bool MemberOfUnknownSpecialization;
388  TemplateName.setIdentifier(NewII, NameLoc);
389  NestedNameSpecifier *NNS = Correction.getCorrectionSpecifier();
390  CXXScopeSpec NewSS, *NewSSPtr = SS;
391  if (SS && NNS) {
392  NewSS.MakeTrivial(Context, NNS, SourceRange(NameLoc));
393  NewSSPtr = &NewSS;
394  }
395  if (Correction && (NNS || NewII != &II) &&
396  // Ignore a correction to a template type as the to-be-corrected
397  // identifier is not a template (typo correction for template names
398  // is handled elsewhere).
399  !(getLangOpts().CPlusPlus && NewSSPtr &&
400  isTemplateName(S, *NewSSPtr, false, TemplateName, nullptr, false,
401  Template, MemberOfUnknownSpecialization))) {
402  ParsedType Ty = getTypeName(*NewII, NameLoc, S, NewSSPtr,
403  isClassName, HasTrailingDot, ObjectTypePtr,
404  IsCtorOrDtorName,
405  WantNontrivialTypeSourceInfo,
406  IsClassTemplateDeductionContext);
407  if (Ty) {
408  diagnoseTypo(Correction,
409  PDiag(diag::err_unknown_type_or_class_name_suggest)
410  << Result.getLookupName() << isClassName);
411  if (SS && NNS)
412  SS->MakeTrivial(Context, NNS, SourceRange(NameLoc));
413  *CorrectedII = NewII;
414  return Ty;
415  }
416  }
417  }
418  // If typo correction failed or was not performed, fall through
419  LLVM_FALLTHROUGH;
422  Result.suppressDiagnostics();
423  return nullptr;
424 
426  // Recover from type-hiding ambiguities by hiding the type. We'll
427  // do the lookup again when looking for an object, and we can
428  // diagnose the error then. If we don't do this, then the error
429  // about hiding the type will be immediately followed by an error
430  // that only makes sense if the identifier was treated like a type.
431  if (Result.getAmbiguityKind() == LookupResult::AmbiguousTagHiding) {
432  Result.suppressDiagnostics();
433  return nullptr;
434  }
435 
436  // Look to see if we have a type anywhere in the list of results.
437  for (LookupResult::iterator Res = Result.begin(), ResEnd = Result.end();
438  Res != ResEnd; ++Res) {
439  NamedDecl *RealRes = (*Res)->getUnderlyingDecl();
440  if (isa<TypeDecl, ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(
441  RealRes) ||
442  (AllowDeducedTemplate && getAsTypeTemplateDecl(RealRes))) {
443  if (!IIDecl ||
444  // Make the selection of the recovery decl deterministic.
445  RealRes->getLocation() < IIDecl->getLocation()) {
446  IIDecl = RealRes;
447  FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Res);
448  }
449  }
450  }
451 
452  if (!IIDecl) {
453  // None of the entities we found is a type, so there is no way
454  // to even assume that the result is a type. In this case, don't
455  // complain about the ambiguity. The parser will either try to
456  // perform this lookup again (e.g., as an object name), which
457  // will produce the ambiguity, or will complain that it expected
458  // a type name.
459  Result.suppressDiagnostics();
460  return nullptr;
461  }
462 
463  // We found a type within the ambiguous lookup; diagnose the
464  // ambiguity and then return that type. This might be the right
465  // answer, or it might not be, but it suppresses any attempt to
466  // perform the name lookup again.
467  break;
468 
469  case LookupResult::Found:
470  IIDecl = Result.getFoundDecl();
471  FoundUsingShadow = dyn_cast<UsingShadowDecl>(*Result.begin());
472  break;
473  }
474 
475  assert(IIDecl && "Didn't find decl");
476 
477  QualType T;
478  if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
479  // C++ [class.qual]p2: A lookup that would find the injected-class-name
480  // instead names the constructors of the class, except when naming a class.
481  // This is ill-formed when we're not actually forming a ctor or dtor name.
482  auto *LookupRD = dyn_cast_or_null<CXXRecordDecl>(LookupCtx);
483  auto *FoundRD = dyn_cast<CXXRecordDecl>(TD);
484  if (!isClassName && !IsCtorOrDtorName && LookupRD && FoundRD &&
485  FoundRD->isInjectedClassName() &&
486  declaresSameEntity(LookupRD, cast<Decl>(FoundRD->getParent())))
487  Diag(NameLoc, diag::err_out_of_line_qualified_id_type_names_constructor)
488  << &II << /*Type*/1;
489 
490  DiagnoseUseOfDecl(IIDecl, NameLoc);
491 
492  T = Context.getTypeDeclType(TD);
493  MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
494  } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
495  (void)DiagnoseUseOfDecl(IDecl, NameLoc);
496  if (!HasTrailingDot)
497  T = Context.getObjCInterfaceType(IDecl);
498  FoundUsingShadow = nullptr; // FIXME: Target must be a TypeDecl.
499  } else if (auto *UD = dyn_cast<UnresolvedUsingIfExistsDecl>(IIDecl)) {
500  (void)DiagnoseUseOfDecl(UD, NameLoc);
501  // Recover with 'int'
502  T = Context.IntTy;
503  FoundUsingShadow = nullptr;
504  } else if (AllowDeducedTemplate) {
505  if (auto *TD = getAsTypeTemplateDecl(IIDecl)) {
506  // FIXME: TemplateName should include FoundUsingShadow sugar.
508  QualType(), false);
509  // Don't wrap in a further UsingType.
510  FoundUsingShadow = nullptr;
511  }
512  }
513 
514  if (T.isNull()) {
515  // If it's not plausibly a type, suppress diagnostics.
516  Result.suppressDiagnostics();
517  return nullptr;
518  }
519 
520  if (FoundUsingShadow)
521  T = Context.getUsingType(FoundUsingShadow, T);
522 
523  // NOTE: avoid constructing an ElaboratedType(Loc) if this is a
524  // constructor or destructor name (in such a case, the scope specifier
525  // will be attached to the enclosing Expr or Decl node).
526  if (SS && SS->isNotEmpty() && !IsCtorOrDtorName &&
527  !isa<ObjCInterfaceDecl, UnresolvedUsingIfExistsDecl>(IIDecl)) {
528  if (WantNontrivialTypeSourceInfo) {
529  // Construct a type with type-source information.
530  TypeLocBuilder Builder;
531  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
532 
533  T = getElaboratedType(ETK_None, *SS, T);
534  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
536  ElabTL.setQualifierLoc(SS->getWithLocInContext(Context));
537  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
538  } else {
539  T = getElaboratedType(ETK_None, *SS, T);
540  }
541  }
542 
543  return ParsedType::make(T);
544 }
545 
546 // Builds a fake NNS for the given decl context.
547 static NestedNameSpecifier *
549  for (;; DC = DC->getLookupParent()) {
550  DC = DC->getPrimaryContext();
551  auto *ND = dyn_cast<NamespaceDecl>(DC);
552  if (ND && !ND->isInline() && !ND->isAnonymousNamespace())
553  return NestedNameSpecifier::Create(Context, nullptr, ND);
554  else if (auto *RD = dyn_cast<CXXRecordDecl>(DC))
555  return NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
556  RD->getTypeForDecl());
557  else if (isa<TranslationUnitDecl>(DC))
558  return NestedNameSpecifier::GlobalSpecifier(Context);
559  }
560  llvm_unreachable("something isn't in TU scope?");
561 }
562 
563 /// Find the parent class with dependent bases of the innermost enclosing method
564 /// context. Do not look for enclosing CXXRecordDecls directly, or we will end
565 /// up allowing unqualified dependent type names at class-level, which MSVC
566 /// correctly rejects.
567 static const CXXRecordDecl *
569  for (; DC && DC->isDependentContext(); DC = DC->getLookupParent()) {
570  DC = DC->getPrimaryContext();
571  if (const auto *MD = dyn_cast<CXXMethodDecl>(DC))
572  if (MD->getParent()->hasAnyDependentBases())
573  return MD->getParent();
574  }
575  return nullptr;
576 }
577 
579  SourceLocation NameLoc,
580  bool IsTemplateTypeArg) {
581  assert(getLangOpts().MSVCCompat && "shouldn't be called in non-MSVC mode");
582 
583  NestedNameSpecifier *NNS = nullptr;
584  if (IsTemplateTypeArg && getCurScope()->isTemplateParamScope()) {
585  // If we weren't able to parse a default template argument, delay lookup
586  // until instantiation time by making a non-dependent DependentTypeName. We
587  // pretend we saw a NestedNameSpecifier referring to the current scope, and
588  // lookup is retried.
589  // FIXME: This hurts our diagnostic quality, since we get errors like "no
590  // type named 'Foo' in 'current_namespace'" when the user didn't write any
591  // name specifiers.
592  NNS = synthesizeCurrentNestedNameSpecifier(Context, CurContext);
593  Diag(NameLoc, diag::ext_ms_delayed_template_argument) << &II;
594  } else if (const CXXRecordDecl *RD =
596  // Build a DependentNameType that will perform lookup into RD at
597  // instantiation time.
598  NNS = NestedNameSpecifier::Create(Context, nullptr, RD->isTemplateDecl(),
599  RD->getTypeForDecl());
600 
601  // Diagnose that this identifier was undeclared, and retry the lookup during
602  // template instantiation.
603  Diag(NameLoc, diag::ext_undeclared_unqual_id_with_dependent_base) << &II
604  << RD;
605  } else {
606  // This is not a situation that we should recover from.
607  return ParsedType();
608  }
609 
610  QualType T = Context.getDependentNameType(ETK_None, NNS, &II);
611 
612  // Build type location information. We synthesized the qualifier, so we have
613  // to build a fake NestedNameSpecifierLoc.
614  NestedNameSpecifierLocBuilder NNSLocBuilder;
615  NNSLocBuilder.MakeTrivial(Context, NNS, SourceRange(NameLoc));
616  NestedNameSpecifierLoc QualifierLoc = NNSLocBuilder.getWithLocInContext(Context);
617 
618  TypeLocBuilder Builder;
619  DependentNameTypeLoc DepTL = Builder.push<DependentNameTypeLoc>(T);
620  DepTL.setNameLoc(NameLoc);
622  DepTL.setQualifierLoc(QualifierLoc);
623  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
624 }
625 
626 /// isTagName() - This method is called *for error recovery purposes only*
627 /// to determine if the specified name is a valid tag name ("struct foo"). If
628 /// so, this returns the TST for the tag corresponding to it (TST_enum,
629 /// TST_union, TST_struct, TST_interface, TST_class). This is used to diagnose
630 /// cases in C where the user forgot to specify the tag.
632  // Do a tag name lookup in this scope.
633  LookupResult R(*this, &II, SourceLocation(), LookupTagName);
634  LookupName(R, S, false);
637  if (const TagDecl *TD = R.getAsSingle<TagDecl>()) {
638  switch (TD->getTagKind()) {
639  case TTK_Struct: return DeclSpec::TST_struct;
641  case TTK_Union: return DeclSpec::TST_union;
642  case TTK_Class: return DeclSpec::TST_class;
643  case TTK_Enum: return DeclSpec::TST_enum;
644  }
645  }
646 
648 }
649 
650 /// isMicrosoftMissingTypename - In Microsoft mode, within class scope,
651 /// if a CXXScopeSpec's type is equal to the type of one of the base classes
652 /// then downgrade the missing typename error to a warning.
653 /// This is needed for MSVC compatibility; Example:
654 /// @code
655 /// template<class T> class A {
656 /// public:
657 /// typedef int TYPE;
658 /// };
659 /// template<class T> class B : public A<T> {
660 /// public:
661 /// A<T>::TYPE a; // no typename required because A<T> is a base class.
662 /// };
663 /// @endcode
665  if (CurContext->isRecord()) {
667  return true;
668 
669  const Type *Ty = SS->getScopeRep()->getAsType();
670 
671  CXXRecordDecl *RD = cast<CXXRecordDecl>(CurContext);
672  for (const auto &Base : RD->bases())
673  if (Ty && Context.hasSameUnqualifiedType(QualType(Ty, 1), Base.getType()))
674  return true;
675  return S->isFunctionPrototypeScope();
676  }
677  return CurContext->isFunctionOrMethod() || S->isFunctionPrototypeScope();
678 }
679 
681  SourceLocation IILoc,
682  Scope *S,
683  CXXScopeSpec *SS,
684  ParsedType &SuggestedType,
685  bool IsTemplateName) {
686  // Don't report typename errors for editor placeholders.
687  if (II->isEditorPlaceholder())
688  return;
689  // We don't have anything to suggest (yet).
690  SuggestedType = nullptr;
691 
692  // There may have been a typo in the name of the type. Look up typo
693  // results, in case we have something that we can suggest.
694  TypeNameValidatorCCC CCC(/*AllowInvalid=*/false, /*WantClass=*/false,
695  /*AllowTemplates=*/IsTemplateName,
696  /*AllowNonTemplates=*/!IsTemplateName);
697  if (TypoCorrection Corrected =
698  CorrectTypo(DeclarationNameInfo(II, IILoc), LookupOrdinaryName, S, SS,
699  CCC, CTK_ErrorRecovery)) {
700  // FIXME: Support error recovery for the template-name case.
701  bool CanRecover = !IsTemplateName;
702  if (Corrected.isKeyword()) {
703  // We corrected to a keyword.
704  diagnoseTypo(Corrected,
705  PDiag(IsTemplateName ? diag::err_no_template_suggest
706  : diag::err_unknown_typename_suggest)
707  << II);
708  II = Corrected.getCorrectionAsIdentifierInfo();
709  } else {
710  // We found a similarly-named type or interface; suggest that.
711  if (!SS || !SS->isSet()) {
712  diagnoseTypo(Corrected,
713  PDiag(IsTemplateName ? diag::err_no_template_suggest
714  : diag::err_unknown_typename_suggest)
715  << II, CanRecover);
716  } else if (DeclContext *DC = computeDeclContext(*SS, false)) {
717  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
718  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
719  II->getName().equals(CorrectedStr);
720  diagnoseTypo(Corrected,
721  PDiag(IsTemplateName
722  ? diag::err_no_member_template_suggest
723  : diag::err_unknown_nested_typename_suggest)
724  << II << DC << DroppedSpecifier << SS->getRange(),
725  CanRecover);
726  } else {
727  llvm_unreachable("could not have corrected a typo here");
728  }
729 
730  if (!CanRecover)
731  return;
732 
733  CXXScopeSpec tmpSS;
734  if (Corrected.getCorrectionSpecifier())
735  tmpSS.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
736  SourceRange(IILoc));
737  // FIXME: Support class template argument deduction here.
738  SuggestedType =
739  getTypeName(*Corrected.getCorrectionAsIdentifierInfo(), IILoc, S,
740  tmpSS.isSet() ? &tmpSS : SS, false, false, nullptr,
741  /*IsCtorOrDtorName=*/false,
742  /*WantNontrivialTypeSourceInfo=*/true);
743  }
744  return;
745  }
746 
747  if (getLangOpts().CPlusPlus && !IsTemplateName) {
748  // See if II is a class template that the user forgot to pass arguments to.
749  UnqualifiedId Name;
750  Name.setIdentifier(II, IILoc);
751  CXXScopeSpec EmptySS;
752  TemplateTy TemplateResult;
753  bool MemberOfUnknownSpecialization;
754  if (isTemplateName(S, SS ? *SS : EmptySS, /*hasTemplateKeyword=*/false,
755  Name, nullptr, true, TemplateResult,
756  MemberOfUnknownSpecialization) == TNK_Type_template) {
757  diagnoseMissingTemplateArguments(TemplateResult.get(), IILoc);
758  return;
759  }
760  }
761 
762  // FIXME: Should we move the logic that tries to recover from a missing tag
763  // (struct, union, enum) from Parser::ParseImplicitInt here, instead?
764 
765  if (!SS || (!SS->isSet() && !SS->isInvalid()))
766  Diag(IILoc, IsTemplateName ? diag::err_no_template
767  : diag::err_unknown_typename)
768  << II;
769  else if (DeclContext *DC = computeDeclContext(*SS, false))
770  Diag(IILoc, IsTemplateName ? diag::err_no_member_template
771  : diag::err_typename_nested_not_found)
772  << II << DC << SS->getRange();
773  else if (SS->isValid() && SS->getScopeRep()->containsErrors()) {
774  SuggestedType =
775  ActOnTypenameType(S, SourceLocation(), *SS, *II, IILoc).get();
776  } else if (isDependentScopeSpecifier(*SS)) {
777  unsigned DiagID = diag::err_typename_missing;
778  if (getLangOpts().MSVCCompat && isMicrosoftMissingTypename(SS, S))
779  DiagID = diag::ext_typename_missing;
780 
781  Diag(SS->getRange().getBegin(), DiagID)
782  << SS->getScopeRep() << II->getName()
783  << SourceRange(SS->getRange().getBegin(), IILoc)
784  << FixItHint::CreateInsertion(SS->getRange().getBegin(), "typename ");
785  SuggestedType = ActOnTypenameType(S, SourceLocation(),
786  *SS, *II, IILoc).get();
787  } else {
788  assert(SS && SS->isInvalid() &&
789  "Invalid scope specifier has already been diagnosed");
790  }
791 }
792 
793 /// Determine whether the given result set contains either a type name
794 /// or
795 static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken) {
796  bool CheckTemplate = R.getSema().getLangOpts().CPlusPlus &&
797  NextToken.is(tok::less);
798 
799  for (LookupResult::iterator I = R.begin(), IEnd = R.end(); I != IEnd; ++I) {
800  if (isa<TypeDecl>(*I) || isa<ObjCInterfaceDecl>(*I))
801  return true;
802 
803  if (CheckTemplate && isa<TemplateDecl>(*I))
804  return true;
805  }
806 
807  return false;
808 }
809 
810 static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result,
811  Scope *S, CXXScopeSpec &SS,
812  IdentifierInfo *&Name,
813  SourceLocation NameLoc) {
814  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupTagName);
815  SemaRef.LookupParsedName(R, S, &SS);
816  if (TagDecl *Tag = R.getAsSingle<TagDecl>()) {
817  StringRef FixItTagName;
818  switch (Tag->getTagKind()) {
819  case TTK_Class:
820  FixItTagName = "class ";
821  break;
822 
823  case TTK_Enum:
824  FixItTagName = "enum ";
825  break;
826 
827  case TTK_Struct:
828  FixItTagName = "struct ";
829  break;
830 
831  case TTK_Interface:
832  FixItTagName = "__interface ";
833  break;
834 
835  case TTK_Union:
836  FixItTagName = "union ";
837  break;
838  }
839 
840  StringRef TagName = FixItTagName.drop_back();
841  SemaRef.Diag(NameLoc, diag::err_use_of_tag_name_without_tag)
842  << Name << TagName << SemaRef.getLangOpts().CPlusPlus
843  << FixItHint::CreateInsertion(NameLoc, FixItTagName);
844 
845  for (LookupResult::iterator I = Result.begin(), IEnd = Result.end();
846  I != IEnd; ++I)
847  SemaRef.Diag((*I)->getLocation(), diag::note_decl_hiding_tag_type)
848  << Name << TagName;
849 
850  // Replace lookup results with just the tag decl.
851  Result.clear(Sema::LookupTagName);
852  SemaRef.LookupParsedName(Result, S, &SS);
853  return true;
854  }
855 
856  return false;
857 }
858 
860  IdentifierInfo *&Name,
861  SourceLocation NameLoc,
862  const Token &NextToken,
864  DeclarationNameInfo NameInfo(Name, NameLoc);
865  ObjCMethodDecl *CurMethod = getCurMethodDecl();
866 
867  assert(NextToken.isNot(tok::coloncolon) &&
868  "parse nested name specifiers before calling ClassifyName");
869  if (getLangOpts().CPlusPlus && SS.isSet() &&
870  isCurrentClassName(*Name, S, &SS)) {
871  // Per [class.qual]p2, this names the constructors of SS, not the
872  // injected-class-name. We don't have a classification for that.
873  // There's not much point caching this result, since the parser
874  // will reject it later.
876  }
877 
878  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
879  LookupParsedName(Result, S, &SS, !CurMethod);
880 
881  if (SS.isInvalid())
882  return NameClassification::Error();
883 
884  // For unqualified lookup in a class template in MSVC mode, look into
885  // dependent base classes where the primary class template is known.
886  if (Result.empty() && SS.isEmpty() && getLangOpts().MSVCCompat) {
887  if (ParsedType TypeInBase =
888  recoverFromTypeInKnownDependentBase(*this, *Name, NameLoc))
889  return TypeInBase;
890  }
891 
892  // Perform lookup for Objective-C instance variables (including automatically
893  // synthesized instance variables), if we're in an Objective-C method.
894  // FIXME: This lookup really, really needs to be folded in to the normal
895  // unqualified lookup mechanism.
896  if (SS.isEmpty() && CurMethod && !isResultTypeOrTemplate(Result, NextToken)) {
897  DeclResult Ivar = LookupIvarInObjCMethod(Result, S, Name);
898  if (Ivar.isInvalid())
899  return NameClassification::Error();
900  if (Ivar.isUsable())
901  return NameClassification::NonType(cast<NamedDecl>(Ivar.get()));
902 
903  // We defer builtin creation until after ivar lookup inside ObjC methods.
904  if (Result.empty())
905  LookupBuiltin(Result);
906  }
907 
908  bool SecondTry = false;
909  bool IsFilteredTemplateName = false;
910 
911 Corrected:
912  switch (Result.getResultKind()) {
914  // If an unqualified-id is followed by a '(', then we have a function
915  // call.
916  if (SS.isEmpty() && NextToken.is(tok::l_paren)) {
917  // In C++, this is an ADL-only call.
918  // FIXME: Reference?
919  if (getLangOpts().CPlusPlus)
920  return NameClassification::UndeclaredNonType();
921 
922  // C90 6.3.2.2:
923  // If the expression that precedes the parenthesized argument list in a
924  // function call consists solely of an identifier, and if no
925  // declaration is visible for this identifier, the identifier is
926  // implicitly declared exactly as if, in the innermost block containing
927  // the function call, the declaration
928  //
929  // extern int identifier ();
930  //
931  // appeared.
932  //
933  // We also allow this in C99 as an extension.
934  if (NamedDecl *D = ImplicitlyDefineFunction(NameLoc, *Name, S))
935  return NameClassification::NonType(D);
936  }
937 
938  if (getLangOpts().CPlusPlus20 && SS.isEmpty() && NextToken.is(tok::less)) {
939  // In C++20 onwards, this could be an ADL-only call to a function
940  // template, and we're required to assume that this is a template name.
941  //
942  // FIXME: Find a way to still do typo correction in this case.
943  TemplateName Template =
944  Context.getAssumedTemplateName(NameInfo.getName());
945  return NameClassification::UndeclaredTemplate(Template);
946  }
947 
948  // In C, we first see whether there is a tag type by the same name, in
949  // which case it's likely that the user just forgot to write "enum",
950  // "struct", or "union".
951  if (!getLangOpts().CPlusPlus && !SecondTry &&
952  isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
953  break;
954  }
955 
956  // Perform typo correction to determine if there is another name that is
957  // close to this name.
958  if (!SecondTry && CCC) {
959  SecondTry = true;
960  if (TypoCorrection Corrected =
961  CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S,
962  &SS, *CCC, CTK_ErrorRecovery)) {
963  unsigned UnqualifiedDiag = diag::err_undeclared_var_use_suggest;
964  unsigned QualifiedDiag = diag::err_no_member_suggest;
965 
966  NamedDecl *FirstDecl = Corrected.getFoundDecl();
967  NamedDecl *UnderlyingFirstDecl = Corrected.getCorrectionDecl();
968  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
969  UnderlyingFirstDecl && isa<TemplateDecl>(UnderlyingFirstDecl)) {
970  UnqualifiedDiag = diag::err_no_template_suggest;
971  QualifiedDiag = diag::err_no_member_template_suggest;
972  } else if (UnderlyingFirstDecl &&
973  (isa<TypeDecl>(UnderlyingFirstDecl) ||
974  isa<ObjCInterfaceDecl>(UnderlyingFirstDecl) ||
975  isa<ObjCCompatibleAliasDecl>(UnderlyingFirstDecl))) {
976  UnqualifiedDiag = diag::err_unknown_typename_suggest;
977  QualifiedDiag = diag::err_unknown_nested_typename_suggest;
978  }
979 
980  if (SS.isEmpty()) {
981  diagnoseTypo(Corrected, PDiag(UnqualifiedDiag) << Name);
982  } else {// FIXME: is this even reachable? Test it.
983  std::string CorrectedStr(Corrected.getAsString(getLangOpts()));
984  bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
985  Name->getName().equals(CorrectedStr);
986  diagnoseTypo(Corrected, PDiag(QualifiedDiag)
987  << Name << computeDeclContext(SS, false)
988  << DroppedSpecifier << SS.getRange());
989  }
990 
991  // Update the name, so that the caller has the new name.
992  Name = Corrected.getCorrectionAsIdentifierInfo();
993 
994  // Typo correction corrected to a keyword.
995  if (Corrected.isKeyword())
996  return Name;
997 
998  // Also update the LookupResult...
999  // FIXME: This should probably go away at some point
1000  Result.clear();
1001  Result.setLookupName(Corrected.getCorrection());
1002  if (FirstDecl)
1003  Result.addDecl(FirstDecl);
1004 
1005  // If we found an Objective-C instance variable, let
1006  // LookupInObjCMethod build the appropriate expression to
1007  // reference the ivar.
1008  // FIXME: This is a gross hack.
1009  if (ObjCIvarDecl *Ivar = Result.getAsSingle<ObjCIvarDecl>()) {
1010  DeclResult R =
1011  LookupIvarInObjCMethod(Result, S, Ivar->getIdentifier());
1012  if (R.isInvalid())
1013  return NameClassification::Error();
1014  if (R.isUsable())
1015  return NameClassification::NonType(Ivar);
1016  }
1017 
1018  goto Corrected;
1019  }
1020  }
1021 
1022  // We failed to correct; just fall through and let the parser deal with it.
1023  Result.suppressDiagnostics();
1024  return NameClassification::Unknown();
1025 
1027  // We performed name lookup into the current instantiation, and there were
1028  // dependent bases, so we treat this result the same way as any other
1029  // dependent nested-name-specifier.
1030 
1031  // C++ [temp.res]p2:
1032  // A name used in a template declaration or definition and that is
1033  // dependent on a template-parameter is assumed not to name a type
1034  // unless the applicable name lookup finds a type name or the name is
1035  // qualified by the keyword typename.
1036  //
1037  // FIXME: If the next token is '<', we might want to ask the parser to
1038  // perform some heroics to see if we actually have a
1039  // template-argument-list, which would indicate a missing 'template'
1040  // keyword here.
1041  return NameClassification::DependentNonType();
1042  }
1043 
1044  case LookupResult::Found:
1047  break;
1048 
1050  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1051  hasAnyAcceptableTemplateNames(Result, /*AllowFunctionTemplates=*/true,
1052  /*AllowDependent=*/false)) {
1053  // C++ [temp.local]p3:
1054  // A lookup that finds an injected-class-name (10.2) can result in an
1055  // ambiguity in certain cases (for example, if it is found in more than
1056  // one base class). If all of the injected-class-names that are found
1057  // refer to specializations of the same class template, and if the name
1058  // is followed by a template-argument-list, the reference refers to the
1059  // class template itself and not a specialization thereof, and is not
1060  // ambiguous.
1061  //
1062  // This filtering can make an ambiguous result into an unambiguous one,
1063  // so try again after filtering out template names.
1064  FilterAcceptableTemplateNames(Result);
1065  if (!Result.isAmbiguous()) {
1066  IsFilteredTemplateName = true;
1067  break;
1068  }
1069  }
1070 
1071  // Diagnose the ambiguity and return an error.
1072  return NameClassification::Error();
1073  }
1074 
1075  if (getLangOpts().CPlusPlus && NextToken.is(tok::less) &&
1076  (IsFilteredTemplateName ||
1077  hasAnyAcceptableTemplateNames(
1078  Result, /*AllowFunctionTemplates=*/true,
1079  /*AllowDependent=*/false,
1080  /*AllowNonTemplateFunctions*/ SS.isEmpty() &&
1081  getLangOpts().CPlusPlus20))) {
1082  // C++ [temp.names]p3:
1083  // After name lookup (3.4) finds that a name is a template-name or that
1084  // an operator-function-id or a literal- operator-id refers to a set of
1085  // overloaded functions any member of which is a function template if
1086  // this is followed by a <, the < is always taken as the delimiter of a
1087  // template-argument-list and never as the less-than operator.
1088  // C++2a [temp.names]p2:
1089  // A name is also considered to refer to a template if it is an
1090  // unqualified-id followed by a < and name lookup finds either one
1091  // or more functions or finds nothing.
1092  if (!IsFilteredTemplateName)
1093  FilterAcceptableTemplateNames(Result);
1094 
1095  bool IsFunctionTemplate;
1096  bool IsVarTemplate;
1097  TemplateName Template;
1098  if (Result.end() - Result.begin() > 1) {
1099  IsFunctionTemplate = true;
1100  Template = Context.getOverloadedTemplateName(Result.begin(),
1101  Result.end());
1102  } else if (!Result.empty()) {
1103  auto *TD = cast<TemplateDecl>(getAsTemplateNameDecl(
1104  *Result.begin(), /*AllowFunctionTemplates=*/true,
1105  /*AllowDependent=*/false));
1106  IsFunctionTemplate = isa<FunctionTemplateDecl>(TD);
1107  IsVarTemplate = isa<VarTemplateDecl>(TD);
1108 
1109  if (SS.isNotEmpty())
1110  Template =
1112  /*TemplateKeyword=*/false, TD);
1113  else
1114  Template = TemplateName(TD);
1115  } else {
1116  // All results were non-template functions. This is a function template
1117  // name.
1118  IsFunctionTemplate = true;
1119  Template = Context.getAssumedTemplateName(NameInfo.getName());
1120  }
1121 
1122  if (IsFunctionTemplate) {
1123  // Function templates always go through overload resolution, at which
1124  // point we'll perform the various checks (e.g., accessibility) we need
1125  // to based on which function we selected.
1126  Result.suppressDiagnostics();
1127 
1128  return NameClassification::FunctionTemplate(Template);
1129  }
1130 
1131  return IsVarTemplate ? NameClassification::VarTemplate(Template)
1132  : NameClassification::TypeTemplate(Template);
1133  }
1134 
1135  auto BuildTypeFor = [&](TypeDecl *Type, NamedDecl *Found) {
1136  QualType T = Context.getTypeDeclType(Type);
1137  if (const auto *USD = dyn_cast<UsingShadowDecl>(Found))
1138  T = Context.getUsingType(USD, T);
1139 
1140  if (SS.isEmpty()) // No elaborated type, trivial location info
1141  return ParsedType::make(T);
1142 
1143  TypeLocBuilder Builder;
1144  Builder.pushTypeSpec(T).setNameLoc(NameLoc);
1145  T = getElaboratedType(ETK_None, SS, T);
1146  ElaboratedTypeLoc ElabTL = Builder.push<ElaboratedTypeLoc>(T);
1148  ElabTL.setQualifierLoc(SS.getWithLocInContext(Context));
1149  return CreateParsedType(T, Builder.getTypeSourceInfo(Context, T));
1150  };
1151 
1152  NamedDecl *FirstDecl = (*Result.begin())->getUnderlyingDecl();
1153  if (TypeDecl *Type = dyn_cast<TypeDecl>(FirstDecl)) {
1154  DiagnoseUseOfDecl(Type, NameLoc);
1155  MarkAnyDeclReferenced(Type->getLocation(), Type, /*OdrUse=*/false);
1156  return BuildTypeFor(Type, *Result.begin());
1157  }
1158 
1159  ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(FirstDecl);
1160  if (!Class) {
1161  // FIXME: It's unfortunate that we don't have a Type node for handling this.
1162  if (ObjCCompatibleAliasDecl *Alias =
1163  dyn_cast<ObjCCompatibleAliasDecl>(FirstDecl))
1164  Class = Alias->getClassInterface();
1165  }
1166 
1167  if (Class) {
1168  DiagnoseUseOfDecl(Class, NameLoc);
1169 
1170  if (NextToken.is(tok::period)) {
1171  // Interface. <something> is parsed as a property reference expression.
1172  // Just return "unknown" as a fall-through for now.
1173  Result.suppressDiagnostics();
1174  return NameClassification::Unknown();
1175  }
1176 
1177  QualType T = Context.getObjCInterfaceType(Class);
1178  return ParsedType::make(T);
1179  }
1180 
1181  if (isa<ConceptDecl>(FirstDecl))
1182  return NameClassification::Concept(
1183  TemplateName(cast<TemplateDecl>(FirstDecl)));
1184 
1185  if (auto *EmptyD = dyn_cast<UnresolvedUsingIfExistsDecl>(FirstDecl)) {
1186  (void)DiagnoseUseOfDecl(EmptyD, NameLoc);
1187  return NameClassification::Error();
1188  }
1189 
1190  // We can have a type template here if we're classifying a template argument.
1191  if (isa<TemplateDecl>(FirstDecl) && !isa<FunctionTemplateDecl>(FirstDecl) &&
1192  !isa<VarTemplateDecl>(FirstDecl))
1193  return NameClassification::TypeTemplate(
1194  TemplateName(cast<TemplateDecl>(FirstDecl)));
1195 
1196  // Check for a tag type hidden by a non-type decl in a few cases where it
1197  // seems likely a type is wanted instead of the non-type that was found.
1198  bool NextIsOp = NextToken.isOneOf(tok::amp, tok::star);
1199  if ((NextToken.is(tok::identifier) ||
1200  (NextIsOp &&
1201  FirstDecl->getUnderlyingDecl()->isFunctionOrFunctionTemplate())) &&
1202  isTagTypeWithMissingTag(*this, Result, S, SS, Name, NameLoc)) {
1203  TypeDecl *Type = Result.getAsSingle<TypeDecl>();
1204  DiagnoseUseOfDecl(Type, NameLoc);
1205  return BuildTypeFor(Type, *Result.begin());
1206  }
1207 
1208  // If we already know which single declaration is referenced, just annotate
1209  // that declaration directly. Defer resolving even non-overloaded class
1210  // member accesses, as we need to defer certain access checks until we know
1211  // the context.
1212  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1213  if (Result.isSingleResult() && !ADL && !FirstDecl->isCXXClassMember())
1214  return NameClassification::NonType(Result.getRepresentativeDecl());
1215 
1216  // Otherwise, this is an overload set that we will need to resolve later.
1217  Result.suppressDiagnostics();
1218  return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
1219  Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
1220  Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1221  Result.begin(), Result.end()));
1222 }
1223 
1224 ExprResult
1226  SourceLocation NameLoc) {
1227  assert(getLangOpts().CPlusPlus && "ADL-only call in C?");
1228  CXXScopeSpec SS;
1229  LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName);
1230  return BuildDeclarationNameExpr(SS, Result, /*ADL=*/true);
1231 }
1232 
1233 ExprResult
1235  IdentifierInfo *Name,
1236  SourceLocation NameLoc,
1237  bool IsAddressOfOperand) {
1238  DeclarationNameInfo NameInfo(Name, NameLoc);
1239  return ActOnDependentIdExpression(SS, /*TemplateKWLoc=*/SourceLocation(),
1240  NameInfo, IsAddressOfOperand,
1241  /*TemplateArgs=*/nullptr);
1242 }
1243 
1245  NamedDecl *Found,
1246  SourceLocation NameLoc,
1247  const Token &NextToken) {
1248  if (getCurMethodDecl() && SS.isEmpty())
1249  if (auto *Ivar = dyn_cast<ObjCIvarDecl>(Found->getUnderlyingDecl()))
1250  return BuildIvarRefExpr(S, NameLoc, Ivar);
1251 
1252  // Reconstruct the lookup result.
1253  LookupResult Result(*this, Found->getDeclName(), NameLoc, LookupOrdinaryName);
1254  Result.addDecl(Found);
1255  Result.resolveKind();
1256 
1257  bool ADL = UseArgumentDependentLookup(SS, Result, NextToken.is(tok::l_paren));
1258  return BuildDeclarationNameExpr(SS, Result, ADL);
1259 }
1260 
1262  // For an implicit class member access, transform the result into a member
1263  // access expression if necessary.
1264  auto *ULE = cast<UnresolvedLookupExpr>(E);
1265  if ((*ULE->decls_begin())->isCXXClassMember()) {
1266  CXXScopeSpec SS;
1267  SS.Adopt(ULE->getQualifierLoc());
1268 
1269  // Reconstruct the lookup result.
1270  LookupResult Result(*this, ULE->getName(), ULE->getNameLoc(),
1271  LookupOrdinaryName);
1272  Result.setNamingClass(ULE->getNamingClass());
1273  for (auto I = ULE->decls_begin(), E = ULE->decls_end(); I != E; ++I)
1274  Result.addDecl(*I, I.getAccess());
1275  Result.resolveKind();
1276  return BuildPossibleImplicitMemberExpr(SS, SourceLocation(), Result,
1277  nullptr, S);
1278  }
1279 
1280  // Otherwise, this is already in the form we needed, and no further checks
1281  // are necessary.
1282  return ULE;
1283 }
1284 
1287  auto *TD = Name.getAsTemplateDecl();
1288  if (!TD)
1289  return TemplateNameKindForDiagnostics::DependentTemplate;
1290  if (isa<ClassTemplateDecl>(TD))
1291  return TemplateNameKindForDiagnostics::ClassTemplate;
1292  if (isa<FunctionTemplateDecl>(TD))
1293  return TemplateNameKindForDiagnostics::FunctionTemplate;
1294  if (isa<VarTemplateDecl>(TD))
1295  return TemplateNameKindForDiagnostics::VarTemplate;
1296  if (isa<TypeAliasTemplateDecl>(TD))
1297  return TemplateNameKindForDiagnostics::AliasTemplate;
1298  if (isa<TemplateTemplateParmDecl>(TD))
1299  return TemplateNameKindForDiagnostics::TemplateTemplateParam;
1300  if (isa<ConceptDecl>(TD))
1301  return TemplateNameKindForDiagnostics::Concept;
1302  return TemplateNameKindForDiagnostics::DependentTemplate;
1303 }
1304 
1306  assert(DC->getLexicalParent() == CurContext &&
1307  "The next DeclContext should be lexically contained in the current one.");
1308  CurContext = DC;
1309  S->setEntity(DC);
1310 }
1311 
1313  assert(CurContext && "DeclContext imbalance!");
1314 
1315  CurContext = CurContext->getLexicalParent();
1316  assert(CurContext && "Popped translation unit!");
1317 }
1318 
1320  Decl *D) {
1321  // Unlike PushDeclContext, the context to which we return is not necessarily
1322  // the containing DC of TD, because the new context will be some pre-existing
1323  // TagDecl definition instead of a fresh one.
1324  auto Result = static_cast<SkippedDefinitionContext>(CurContext);
1325  CurContext = cast<TagDecl>(D)->getDefinition();
1326  assert(CurContext && "skipping definition of undefined tag");
1327  // Start lookups from the parent of the current context; we don't want to look
1328  // into the pre-existing complete definition.
1329  S->setEntity(CurContext->getLookupParent());
1330  return Result;
1331 }
1332 
1334  CurContext = static_cast<decltype(CurContext)>(Context);
1335 }
1336 
1337 /// EnterDeclaratorContext - Used when we must lookup names in the context
1338 /// of a declarator's nested name specifier.
1339 ///
1341  // C++0x [basic.lookup.unqual]p13:
1342  // A name used in the definition of a static data member of class
1343  // X (after the qualified-id of the static member) is looked up as
1344  // if the name was used in a member function of X.
1345  // C++0x [basic.lookup.unqual]p14:
1346  // If a variable member of a namespace is defined outside of the
1347  // scope of its namespace then any name used in the definition of
1348  // the variable member (after the declarator-id) is looked up as
1349  // if the definition of the variable member occurred in its
1350  // namespace.
1351  // Both of these imply that we should push a scope whose context
1352  // is the semantic context of the declaration. We can't use
1353  // PushDeclContext here because that context is not necessarily
1354  // lexically contained in the current context. Fortunately,
1355  // the containing scope should have the appropriate information.
1356 
1357  assert(!S->getEntity() && "scope already has entity");
1358 
1359 #ifndef NDEBUG
1360  Scope *Ancestor = S->getParent();
1361  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1362  assert(Ancestor->getEntity() == CurContext && "ancestor context mismatch");
1363 #endif
1364 
1365  CurContext = DC;
1366  S->setEntity(DC);
1367 
1368  if (S->getParent()->isTemplateParamScope()) {
1369  // Also set the corresponding entities for all immediately-enclosing
1370  // template parameter scopes.
1371  EnterTemplatedContext(S->getParent(), DC);
1372  }
1373 }
1374 
1376  assert(S->getEntity() == CurContext && "Context imbalance!");
1377 
1378  // Switch back to the lexical context. The safety of this is
1379  // enforced by an assert in EnterDeclaratorContext.
1380  Scope *Ancestor = S->getParent();
1381  while (!Ancestor->getEntity()) Ancestor = Ancestor->getParent();
1382  CurContext = Ancestor->getEntity();
1383 
1384  // We don't need to do anything with the scope, which is going to
1385  // disappear.
1386 }
1387 
1389  assert(S->isTemplateParamScope() &&
1390  "expected to be initializing a template parameter scope");
1391 
1392  // C++20 [temp.local]p7:
1393  // In the definition of a member of a class template that appears outside
1394  // of the class template definition, the name of a member of the class
1395  // template hides the name of a template-parameter of any enclosing class
1396  // templates (but not a template-parameter of the member if the member is a
1397  // class or function template).
1398  // C++20 [temp.local]p9:
1399  // In the definition of a class template or in the definition of a member
1400  // of such a template that appears outside of the template definition, for
1401  // each non-dependent base class (13.8.2.1), if the name of the base class
1402  // or the name of a member of the base class is the same as the name of a
1403  // template-parameter, the base class name or member name hides the
1404  // template-parameter name (6.4.10).
1405  //
1406  // This means that a template parameter scope should be searched immediately
1407  // after searching the DeclContext for which it is a template parameter
1408  // scope. For example, for
1409  // template<typename T> template<typename U> template<typename V>
1410  // void N::A<T>::B<U>::f(...)
1411  // we search V then B<U> (and base classes) then U then A<T> (and base
1412  // classes) then T then N then ::.
1413  unsigned ScopeDepth = getTemplateDepth(S);
1414  for (; S && S->isTemplateParamScope(); S = S->getParent(), --ScopeDepth) {
1415  DeclContext *SearchDCAfterScope = DC;
1416  for (; DC; DC = DC->getLookupParent()) {
1417  if (const TemplateParameterList *TPL =
1418  cast<Decl>(DC)->getDescribedTemplateParams()) {
1419  unsigned DCDepth = TPL->getDepth() + 1;
1420  if (DCDepth > ScopeDepth)
1421  continue;
1422  if (ScopeDepth == DCDepth)
1423  SearchDCAfterScope = DC = DC->getLookupParent();
1424  break;
1425  }
1426  }
1427  S->setLookupEntity(SearchDCAfterScope);
1428  }
1429 }
1430 
1432  // We assume that the caller has already called
1433  // ActOnReenterTemplateScope so getTemplatedDecl() works.
1434  FunctionDecl *FD = D->getAsFunction();
1435  if (!FD)
1436  return;
1437 
1438  // Same implementation as PushDeclContext, but enters the context
1439  // from the lexical parent, rather than the top-level class.
1440  assert(CurContext == FD->getLexicalParent() &&
1441  "The next DeclContext should be lexically contained in the current one.");
1442  CurContext = FD;
1443  S->setEntity(CurContext);
1444 
1445  for (unsigned P = 0, NumParams = FD->getNumParams(); P < NumParams; ++P) {
1446  ParmVarDecl *Param = FD->getParamDecl(P);
1447  // If the parameter has an identifier, then add it to the scope
1448  if (Param->getIdentifier()) {
1449  S->AddDecl(Param);
1450  IdResolver.AddDecl(Param);
1451  }
1452  }
1453 }
1454 
1456  // Same implementation as PopDeclContext, but returns to the lexical parent,
1457  // rather than the top-level class.
1458  assert(CurContext && "DeclContext imbalance!");
1459  CurContext = CurContext->getLexicalParent();
1460  assert(CurContext && "Popped translation unit!");
1461 }
1462 
1463 /// Determine whether overloading is allowed for a new function
1464 /// declaration considering prior declarations of the same name.
1465 ///
1466 /// This routine determines whether overloading is possible, not
1467 /// whether a new declaration actually overloads a previous one.
1468 /// It will return true in C++ (where overloads are alway permitted)
1469 /// or, as a C extension, when either the new declaration or a
1470 /// previous one is declared with the 'overloadable' attribute.
1472  ASTContext &Context,
1473  const FunctionDecl *New) {
1474  if (Context.getLangOpts().CPlusPlus || New->hasAttr<OverloadableAttr>())
1475  return true;
1476 
1477  // Multiversion function declarations are not overloads in the
1478  // usual sense of that term, but lookup will report that an
1479  // overload set was found if more than one multiversion function
1480  // declaration is present for the same name. It is therefore
1481  // inadequate to assume that some prior declaration(s) had
1482  // the overloadable attribute; checking is required. Since one
1483  // declaration is permitted to omit the attribute, it is necessary
1484  // to check at least two; hence the 'any_of' check below. Note that
1485  // the overloadable attribute is implicitly added to declarations
1486  // that were required to have it but did not.
1487  if (Previous.getResultKind() == LookupResult::FoundOverloaded) {
1488  return llvm::any_of(Previous, [](const NamedDecl *ND) {
1489  return ND->hasAttr<OverloadableAttr>();
1490  });
1491  } else if (Previous.getResultKind() == LookupResult::Found)
1492  return Previous.getFoundDecl()->hasAttr<OverloadableAttr>();
1493 
1494  return false;
1495 }
1496 
1497 /// Add this decl to the scope shadowed decl chains.
1498 void Sema::PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext) {
1499  // Move up the scope chain until we find the nearest enclosing
1500  // non-transparent context. The declaration will be introduced into this
1501  // scope.
1502  while (S->getEntity() && S->getEntity()->isTransparentContext())
1503  S = S->getParent();
1504 
1505  // Add scoped declarations into their context, so that they can be
1506  // found later. Declarations without a context won't be inserted
1507  // into any context.
1508  if (AddToContext)
1509  CurContext->addDecl(D);
1510 
1511  // Out-of-line definitions shouldn't be pushed into scope in C++, unless they
1512  // are function-local declarations.
1513  if (getLangOpts().CPlusPlus && D->isOutOfLine() && !S->getFnParent())
1514  return;
1515 
1516  // Template instantiations should also not be pushed into scope.
1517  if (isa<FunctionDecl>(D) &&
1518  cast<FunctionDecl>(D)->isFunctionTemplateSpecialization())
1519  return;
1520 
1521  // If this replaces anything in the current scope,
1522  IdentifierResolver::iterator I = IdResolver.begin(D->getDeclName()),
1523  IEnd = IdResolver.end();
1524  for (; I != IEnd; ++I) {
1525  if (S->isDeclScope(*I) && D->declarationReplaces(*I)) {
1526  S->RemoveDecl(*I);
1527  IdResolver.RemoveDecl(*I);
1528 
1529  // Should only need to replace one decl.
1530  break;
1531  }
1532  }
1533 
1534  S->AddDecl(D);
1535 
1536  if (isa<LabelDecl>(D) && !cast<LabelDecl>(D)->isGnuLocal()) {
1537  // Implicitly-generated labels may end up getting generated in an order that
1538  // isn't strictly lexical, which breaks name lookup. Be careful to insert
1539  // the label at the appropriate place in the identifier chain.
1540  for (I = IdResolver.begin(D->getDeclName()); I != IEnd; ++I) {
1541  DeclContext *IDC = (*I)->getLexicalDeclContext()->getRedeclContext();
1542  if (IDC == CurContext) {
1543  if (!S->isDeclScope(*I))
1544  continue;
1545  } else if (IDC->Encloses(CurContext))
1546  break;
1547  }
1548 
1549  IdResolver.InsertDeclAfter(I, D);
1550  } else {
1551  IdResolver.AddDecl(D);
1552  }
1553  warnOnReservedIdentifier(D);
1554 }
1555 
1557  bool AllowInlineNamespace) {
1558  return IdResolver.isDeclInScope(D, Ctx, S, AllowInlineNamespace);
1559 }
1560 
1562  DeclContext *TargetDC = DC->getPrimaryContext();
1563  do {
1564  if (DeclContext *ScopeDC = S->getEntity())
1565  if (ScopeDC->getPrimaryContext() == TargetDC)
1566  return S;
1567  } while ((S = S->getParent()));
1568 
1569  return nullptr;
1570 }
1571 
1573  DeclContext*,
1574  ASTContext&);
1575 
1576 /// Filters out lookup results that don't fall within the given scope
1577 /// as determined by isDeclInScope.
1579  bool ConsiderLinkage,
1580  bool AllowInlineNamespace) {
1582  while (F.hasNext()) {
1583  NamedDecl *D = F.next();
1584 
1585  if (isDeclInScope(D, Ctx, S, AllowInlineNamespace))
1586  continue;
1587 
1588  if (ConsiderLinkage && isOutOfScopePreviousDeclaration(D, Ctx, Context))
1589  continue;
1590 
1591  F.erase();
1592  }
1593 
1594  F.done();
1595 }
1596 
1597 /// We've determined that \p New is a redeclaration of \p Old. Check that they
1598 /// have compatible owning modules.
1600  // [module.interface]p7:
1601  // A declaration is attached to a module as follows:
1602  // - If the declaration is a non-dependent friend declaration that nominates a
1603  // function with a declarator-id that is a qualified-id or template-id or that
1604  // nominates a class other than with an elaborated-type-specifier with neither
1605  // a nested-name-specifier nor a simple-template-id, it is attached to the
1606  // module to which the friend is attached ([basic.link]).
1607  if (New->getFriendObjectKind() &&
1610  makeMergedDefinitionVisible(New);
1611  return false;
1612  }
1613 
1614  Module *NewM = New->getOwningModule();
1615  Module *OldM = Old->getOwningModule();
1616 
1617  if (NewM && NewM->Kind == Module::PrivateModuleFragment)
1618  NewM = NewM->Parent;
1619  if (OldM && OldM->Kind == Module::PrivateModuleFragment)
1620  OldM = OldM->Parent;
1621 
1622  // If we have a decl in a module partition, it is part of the containing
1623  // module (which is the only thing that can be importing it).
1624  if (NewM && OldM &&
1627  return false;
1628  }
1629 
1630  if (NewM == OldM)
1631  return false;
1632 
1633  bool NewIsModuleInterface = NewM && NewM->isModulePurview();
1634  bool OldIsModuleInterface = OldM && OldM->isModulePurview();
1635  if (NewIsModuleInterface || OldIsModuleInterface) {
1636  // C++ Modules TS [basic.def.odr] 6.2/6.7 [sic]:
1637  // if a declaration of D [...] appears in the purview of a module, all
1638  // other such declarations shall appear in the purview of the same module
1639  Diag(New->getLocation(), diag::err_mismatched_owning_module)
1640  << New
1641  << NewIsModuleInterface
1642  << (NewIsModuleInterface ? NewM->getFullModuleName() : "")
1643  << OldIsModuleInterface
1644  << (OldIsModuleInterface ? OldM->getFullModuleName() : "");
1645  Diag(Old->getLocation(), diag::note_previous_declaration);
1646  New->setInvalidDecl();
1647  return true;
1648  }
1649 
1650  return false;
1651 }
1652 
1653 // [module.interface]p6:
1654 // A redeclaration of an entity X is implicitly exported if X was introduced by
1655 // an exported declaration; otherwise it shall not be exported.
1657  // [module.interface]p1:
1658  // An export-declaration shall inhabit a namespace scope.
1659  //
1660  // So it is meaningless to talk about redeclaration which is not at namespace
1661  // scope.
1662  if (!New->getLexicalDeclContext()
1664  ->isFileContext() ||
1665  !Old->getLexicalDeclContext()
1667  ->isFileContext())
1668  return false;
1669 
1670  bool IsNewExported = New->isInExportDeclContext();
1671  bool IsOldExported = Old->isInExportDeclContext();
1672 
1673  // It should be irrevelant if both of them are not exported.
1674  if (!IsNewExported && !IsOldExported)
1675  return false;
1676 
1677  if (IsOldExported)
1678  return false;
1679 
1680  assert(IsNewExported);
1681 
1682  Diag(New->getLocation(), diag::err_redeclaration_non_exported) << New;
1683  Diag(Old->getLocation(), diag::note_previous_declaration);
1684  return true;
1685 }
1686 
1687 // A wrapper function for checking the semantic restrictions of
1688 // a redeclaration within a module.
1690  if (CheckRedeclarationModuleOwnership(New, Old))
1691  return true;
1692 
1693  if (CheckRedeclarationExported(New, Old))
1694  return true;
1695 
1696  return false;
1697 }
1698 
1699 static bool isUsingDecl(NamedDecl *D) {
1700  return isa<UsingShadowDecl>(D) ||
1701  isa<UnresolvedUsingTypenameDecl>(D) ||
1702  isa<UnresolvedUsingValueDecl>(D);
1703 }
1704 
1705 /// Removes using shadow declarations from the lookup results.
1708  while (F.hasNext())
1709  if (isUsingDecl(F.next()))
1710  F.erase();
1711 
1712  F.done();
1713 }
1714 
1715 /// Check for this common pattern:
1716 /// @code
1717 /// class S {
1718 /// S(const S&); // DO NOT IMPLEMENT
1719 /// void operator=(const S&); // DO NOT IMPLEMENT
1720 /// };
1721 /// @endcode
1723  // FIXME: Should check for private access too but access is set after we get
1724  // the decl here.
1726  return false;
1727 
1728  if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
1729  return CD->isCopyConstructor();
1730  return D->isCopyAssignmentOperator();
1731 }
1732 
1733 // We need this to handle
1734 //
1735 // typedef struct {
1736 // void *foo() { return 0; }
1737 // } A;
1738 //
1739 // When we see foo we don't know if after the typedef we will get 'A' or '*A'
1740 // for example. If 'A', foo will have external linkage. If we have '*A',
1741 // foo will have no linkage. Since we can't know until we get to the end
1742 // of the typedef, this function finds out if D might have non-external linkage.
1743 // Callers should verify at the end of the TU if it D has external linkage or
1744 // not.
1745 bool Sema::mightHaveNonExternalLinkage(const DeclaratorDecl *D) {
1746  const DeclContext *DC = D->getDeclContext();
1747  while (!DC->isTranslationUnit()) {
1748  if (const RecordDecl *RD = dyn_cast<RecordDecl>(DC)){
1749  if (!RD->hasNameForLinkage())
1750  return true;
1751  }
1752  DC = DC->getParent();
1753  }
1754 
1755  return !D->isExternallyVisible();
1756 }
1757 
1758 // FIXME: This needs to be refactored; some other isInMainFile users want
1759 // these semantics.
1760 static bool isMainFileLoc(const Sema &S, SourceLocation Loc) {
1761  if (S.TUKind != TU_Complete)
1762  return false;
1763  return S.SourceMgr.isInMainFile(Loc);
1764 }
1765 
1767  assert(D);
1768 
1769  if (D->isInvalidDecl() || D->isUsed() || D->hasAttr<UnusedAttr>())
1770  return false;
1771 
1772  // Ignore all entities declared within templates, and out-of-line definitions
1773  // of members of class templates.
1774  if (D->getDeclContext()->isDependentContext() ||
1776  return false;
1777 
1778  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1779  if (FD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1780  return false;
1781  // A non-out-of-line declaration of a member specialization was implicitly
1782  // instantiated; it's the out-of-line declaration that we're interested in.
1783  if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1784  FD->getMemberSpecializationInfo() && !FD->isOutOfLine())
1785  return false;
1786 
1787  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1788  if (MD->isVirtual() || IsDisallowedCopyOrAssign(MD))
1789  return false;
1790  } else {
1791  // 'static inline' functions are defined in headers; don't warn.
1792  if (FD->isInlined() && !isMainFileLoc(*this, FD->getLocation()))
1793  return false;
1794  }
1795 
1796  if (FD->doesThisDeclarationHaveABody() &&
1797  Context.DeclMustBeEmitted(FD))
1798  return false;
1799  } else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1800  // Constants and utility variables are defined in headers with internal
1801  // linkage; don't warn. (Unlike functions, there isn't a convenient marker
1802  // like "inline".)
1803  if (!isMainFileLoc(*this, VD->getLocation()))
1804  return false;
1805 
1806  if (Context.DeclMustBeEmitted(VD))
1807  return false;
1808 
1809  if (VD->isStaticDataMember() &&
1810  VD->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
1811  return false;
1812  if (VD->isStaticDataMember() &&
1813  VD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
1814  VD->getMemberSpecializationInfo() && !VD->isOutOfLine())
1815  return false;
1816 
1817  if (VD->isInline() && !isMainFileLoc(*this, VD->getLocation()))
1818  return false;
1819  } else {
1820  return false;
1821  }
1822 
1823  // Only warn for unused decls internal to the translation unit.
1824  // FIXME: This seems like a bogus check; it suppresses -Wunused-function
1825  // for inline functions defined in the main source file, for instance.
1826  return mightHaveNonExternalLinkage(D);
1827 }
1828 
1830  if (!D)
1831  return;
1832 
1833  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1834  const FunctionDecl *First = FD->getFirstDecl();
1835  if (FD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1836  return; // First should already be in the vector.
1837  }
1838 
1839  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1840  const VarDecl *First = VD->getFirstDecl();
1841  if (VD != First && ShouldWarnIfUnusedFileScopedDecl(First))
1842  return; // First should already be in the vector.
1843  }
1844 
1845  if (ShouldWarnIfUnusedFileScopedDecl(D))
1846  UnusedFileScopedDecls.push_back(D);
1847 }
1848 
1849 static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D) {
1850  if (D->isInvalidDecl())
1851  return false;
1852 
1853  if (auto *DD = dyn_cast<DecompositionDecl>(D)) {
1854  // For a decomposition declaration, warn if none of the bindings are
1855  // referenced, instead of if the variable itself is referenced (which
1856  // it is, by the bindings' expressions).
1857  for (auto *BD : DD->bindings())
1858  if (BD->isReferenced())
1859  return false;
1860  } else if (!D->getDeclName()) {
1861  return false;
1862  } else if (D->isReferenced() || D->isUsed()) {
1863  return false;
1864  }
1865 
1866  if (D->hasAttr<UnusedAttr>() || D->hasAttr<ObjCPreciseLifetimeAttr>())
1867  return false;
1868 
1869  if (isa<LabelDecl>(D))
1870  return true;
1871 
1872  // Except for labels, we only care about unused decls that are local to
1873  // functions.
1874  bool WithinFunction = D->getDeclContext()->isFunctionOrMethod();
1875  if (const auto *R = dyn_cast<CXXRecordDecl>(D->getDeclContext()))
1876  // For dependent types, the diagnostic is deferred.
1877  WithinFunction =
1878  WithinFunction || (R->isLocalClass() && !R->isDependentType());
1879  if (!WithinFunction)
1880  return false;
1881 
1882  if (isa<TypedefNameDecl>(D))
1883  return true;
1884 
1885  // White-list anything that isn't a local variable.
1886  if (!isa<VarDecl>(D) || isa<ParmVarDecl>(D) || isa<ImplicitParamDecl>(D))
1887  return false;
1888 
1889  // Types of valid local variables should be complete, so this should succeed.
1890  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1891 
1892  // White-list anything with an __attribute__((unused)) type.
1893  const auto *Ty = VD->getType().getTypePtr();
1894 
1895  // Only look at the outermost level of typedef.
1896  if (const TypedefType *TT = Ty->getAs<TypedefType>()) {
1897  if (TT->getDecl()->hasAttr<UnusedAttr>())
1898  return false;
1899  }
1900 
1901  // If we failed to complete the type for some reason, or if the type is
1902  // dependent, don't diagnose the variable.
1903  if (Ty->isIncompleteType() || Ty->isDependentType())
1904  return false;
1905 
1906  // Look at the element type to ensure that the warning behaviour is
1907  // consistent for both scalars and arrays.
1908  Ty = Ty->getBaseElementTypeUnsafe();
1909 
1910  if (const TagType *TT = Ty->getAs<TagType>()) {
1911  const TagDecl *Tag = TT->getDecl();
1912  if (Tag->hasAttr<UnusedAttr>())
1913  return false;
1914 
1915  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
1916  if (!RD->hasTrivialDestructor() && !RD->hasAttr<WarnUnusedAttr>())
1917  return false;
1918 
1919  if (const Expr *Init = VD->getInit()) {
1920  if (const ExprWithCleanups *Cleanups =
1921  dyn_cast<ExprWithCleanups>(Init))
1922  Init = Cleanups->getSubExpr();
1923  const CXXConstructExpr *Construct =
1924  dyn_cast<CXXConstructExpr>(Init);
1925  if (Construct && !Construct->isElidable()) {
1926  CXXConstructorDecl *CD = Construct->getConstructor();
1927  if (!CD->isTrivial() && !RD->hasAttr<WarnUnusedAttr>() &&
1928  (VD->getInit()->isValueDependent() || !VD->evaluateValue()))
1929  return false;
1930  }
1931 
1932  // Suppress the warning if we don't know how this is constructed, and
1933  // it could possibly be non-trivial constructor.
1934  if (Init->isTypeDependent())
1935  for (const CXXConstructorDecl *Ctor : RD->ctors())
1936  if (!Ctor->isTrivial())
1937  return false;
1938  }
1939  }
1940  }
1941 
1942  // TODO: __attribute__((unused)) templates?
1943  }
1944 
1945  return true;
1946 }
1947 
1948 static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx,
1949  FixItHint &Hint) {
1950  if (isa<LabelDecl>(D)) {
1952  D->getEndLoc(), tok::colon, Ctx.getSourceManager(), Ctx.getLangOpts(),
1953  true);
1954  if (AfterColon.isInvalid())
1955  return;
1956  Hint = FixItHint::CreateRemoval(
1957  CharSourceRange::getCharRange(D->getBeginLoc(), AfterColon));
1958  }
1959 }
1960 
1962  if (D->getTypeForDecl()->isDependentType())
1963  return;
1964 
1965  for (auto *TmpD : D->decls()) {
1966  if (const auto *T = dyn_cast<TypedefNameDecl>(TmpD))
1967  DiagnoseUnusedDecl(T);
1968  else if(const auto *R = dyn_cast<RecordDecl>(TmpD))
1969  DiagnoseUnusedNestedTypedefs(R);
1970  }
1971 }
1972 
1973 /// DiagnoseUnusedDecl - Emit warnings about declarations that are not used
1974 /// unless they are marked attr(unused).
1976  if (!ShouldDiagnoseUnusedDecl(D))
1977  return;
1978 
1979  if (auto *TD = dyn_cast<TypedefNameDecl>(D)) {
1980  // typedefs can be referenced later on, so the diagnostics are emitted
1981  // at end-of-translation-unit.
1982  UnusedLocalTypedefNameCandidates.insert(TD);
1983  return;
1984  }
1985 
1986  FixItHint Hint;
1987  GenerateFixForUnusedDecl(D, Context, Hint);
1988 
1989  unsigned DiagID;
1990  if (isa<VarDecl>(D) && cast<VarDecl>(D)->isExceptionVariable())
1991  DiagID = diag::warn_unused_exception_param;
1992  else if (isa<LabelDecl>(D))
1993  DiagID = diag::warn_unused_label;
1994  else
1995  DiagID = diag::warn_unused_variable;
1996 
1997  Diag(D->getLocation(), DiagID) << D << Hint;
1998 }
1999 
2001  // If it's not referenced, it can't be set. If it has the Cleanup attribute,
2002  // it's not really unused.
2003  if (!VD->isReferenced() || !VD->getDeclName() || VD->hasAttr<UnusedAttr>() ||
2004  VD->hasAttr<CleanupAttr>())
2005  return;
2006 
2007  const auto *Ty = VD->getType().getTypePtr()->getBaseElementTypeUnsafe();
2008 
2009  if (Ty->isReferenceType() || Ty->isDependentType())
2010  return;
2011 
2012  if (const TagType *TT = Ty->getAs<TagType>()) {
2013  const TagDecl *Tag = TT->getDecl();
2014  if (Tag->hasAttr<UnusedAttr>())
2015  return;
2016  // In C++, don't warn for record types that don't have WarnUnusedAttr, to
2017  // mimic gcc's behavior.
2018  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Tag)) {
2019  if (!RD->hasAttr<WarnUnusedAttr>())
2020  return;
2021  }
2022  }
2023 
2024  // Don't warn about __block Objective-C pointer variables, as they might
2025  // be assigned in the block but not used elsewhere for the purpose of lifetime
2026  // extension.
2027  if (VD->hasAttr<BlocksAttr>() && Ty->isObjCObjectPointerType())
2028  return;
2029 
2030  // Don't warn about Objective-C pointer variables with precise lifetime
2031  // semantics; they can be used to ensure ARC releases the object at a known
2032  // time, which may mean assignment but no other references.
2033  if (VD->hasAttr<ObjCPreciseLifetimeAttr>() && Ty->isObjCObjectPointerType())
2034  return;
2035 
2036  auto iter = RefsMinusAssignments.find(VD);
2037  if (iter == RefsMinusAssignments.end())
2038  return;
2039 
2040  assert(iter->getSecond() >= 0 &&
2041  "Found a negative number of references to a VarDecl");
2042  if (iter->getSecond() != 0)
2043  return;
2044  unsigned DiagID = isa<ParmVarDecl>(VD) ? diag::warn_unused_but_set_parameter
2045  : diag::warn_unused_but_set_variable;
2046  Diag(VD->getLocation(), DiagID) << VD;
2047 }
2048 
2049 static void CheckPoppedLabel(LabelDecl *L, Sema &S) {
2050  // Verify that we have no forward references left. If so, there was a goto
2051  // or address of a label taken, but no definition of it. Label fwd
2052  // definitions are indicated with a null substmt which is also not a resolved
2053  // MS inline assembly label name.
2054  bool Diagnose = false;
2055  if (L->isMSAsmLabel())
2056  Diagnose = !L->isResolvedMSAsmLabel();
2057  else
2058  Diagnose = L->getStmt() == nullptr;
2059  if (Diagnose)
2060  S.Diag(L->getLocation(), diag::err_undeclared_label_use) << L;
2061 }
2062 
2064  S->mergeNRVOIntoParent();
2065 
2066  if (S->decl_empty()) return;
2067  assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
2068  "Scope shouldn't contain decls!");
2069 
2070  for (auto *TmpD : S->decls()) {
2071  assert(TmpD && "This decl didn't get pushed??");
2072 
2073  assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
2074  NamedDecl *D = cast<NamedDecl>(TmpD);
2075 
2076  // Diagnose unused variables in this scope.
2077  if (!S->hasUnrecoverableErrorOccurred()) {
2078  DiagnoseUnusedDecl(D);
2079  if (const auto *RD = dyn_cast<RecordDecl>(D))
2080  DiagnoseUnusedNestedTypedefs(RD);
2081  if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2082  DiagnoseUnusedButSetDecl(VD);
2083  RefsMinusAssignments.erase(VD);
2084  }
2085  }
2086 
2087  if (!D->getDeclName()) continue;
2088 
2089  // If this was a forward reference to a label, verify it was defined.
2090  if (LabelDecl *LD = dyn_cast<LabelDecl>(D))
2091  CheckPoppedLabel(LD, *this);
2092 
2093  // Remove this name from our lexical scope, and warn on it if we haven't
2094  // already.
2095  IdResolver.RemoveDecl(D);
2096  auto ShadowI = ShadowingDecls.find(D);
2097  if (ShadowI != ShadowingDecls.end()) {
2098  if (const auto *FD = dyn_cast<FieldDecl>(ShadowI->second)) {
2099  Diag(D->getLocation(), diag::warn_ctor_parm_shadows_field)
2100  << D << FD << FD->getParent();
2101  Diag(FD->getLocation(), diag::note_previous_declaration);
2102  }
2103  ShadowingDecls.erase(ShadowI);
2104  }
2105  }
2106 }
2107 
2108 /// Look for an Objective-C class in the translation unit.
2109 ///
2110 /// \param Id The name of the Objective-C class we're looking for. If
2111 /// typo-correction fixes this name, the Id will be updated
2112 /// to the fixed name.
2113 ///
2114 /// \param IdLoc The location of the name in the translation unit.
2115 ///
2116 /// \param DoTypoCorrection If true, this routine will attempt typo correction
2117 /// if there is no class with the given name.
2118 ///
2119 /// \returns The declaration of the named Objective-C class, or NULL if the
2120 /// class could not be found.
2122  SourceLocation IdLoc,
2123  bool DoTypoCorrection) {
2124  // The third "scope" argument is 0 since we aren't enabling lazy built-in
2125  // creation from this context.
2126  NamedDecl *IDecl = LookupSingleName(TUScope, Id, IdLoc, LookupOrdinaryName);
2127 
2128  if (!IDecl && DoTypoCorrection) {
2129  // Perform typo correction at the given location, but only if we
2130  // find an Objective-C class name.
2132  if (TypoCorrection C =
2133  CorrectTypo(DeclarationNameInfo(Id, IdLoc), LookupOrdinaryName,
2134  TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
2135  diagnoseTypo(C, PDiag(diag::err_undef_interface_suggest) << Id);
2136  IDecl = C.getCorrectionDeclAs<ObjCInterfaceDecl>();
2137  Id = IDecl->getIdentifier();
2138  }
2139  }
2140  ObjCInterfaceDecl *Def = dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
2141  // This routine must always return a class definition, if any.
2142  if (Def && Def->getDefinition())
2143  Def = Def->getDefinition();
2144  return Def;
2145 }
2146 
2147 /// getNonFieldDeclScope - Retrieves the innermost scope, starting
2148 /// from S, where a non-field would be declared. This routine copes
2149 /// with the difference between C and C++ scoping rules in structs and
2150 /// unions. For example, the following code is well-formed in C but
2151 /// ill-formed in C++:
2152 /// @code
2153 /// struct S6 {
2154 /// enum { BAR } e;
2155 /// };
2156 ///
2157 /// void test_S6() {
2158 /// struct S6 a;
2159 /// a.e = BAR;
2160 /// }
2161 /// @endcode
2162 /// For the declaration of BAR, this routine will return a different
2163 /// scope. The scope S will be the scope of the unnamed enumeration
2164 /// within S6. In C++, this routine will return the scope associated
2165 /// with S6, because the enumeration's scope is a transparent
2166 /// context but structures can contain non-field names. In C, this
2167 /// routine will return the translation unit scope, since the
2168 /// enumeration's scope is a transparent context and structures cannot
2169 /// contain non-field names.
2171  while (((S->getFlags() & Scope::DeclScope) == 0) ||
2172  (S->getEntity() && S->getEntity()->isTransparentContext()) ||
2173  (S->isClassScope() && !getLangOpts().CPlusPlus))
2174  S = S->getParent();
2175  return S;
2176 }
2177 
2178 static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID,
2180  switch (Error) {
2181  case ASTContext::GE_None:
2182  return "";
2184  return BuiltinInfo.getHeaderName(ID);
2186  return "stdio.h";
2188  return "setjmp.h";
2190  return "ucontext.h";
2191  }
2192  llvm_unreachable("unhandled error kind");
2193 }
2194 
2196  unsigned ID, SourceLocation Loc) {
2198 
2199  if (getLangOpts().CPlusPlus) {
2200  LinkageSpecDecl *CLinkageDecl = LinkageSpecDecl::Create(
2201  Context, Parent, Loc, Loc, LinkageSpecDecl::lang_c, false);
2202  CLinkageDecl->setImplicit();
2203  Parent->addDecl(CLinkageDecl);
2204  Parent = CLinkageDecl;
2205  }
2206 
2207  FunctionDecl *New = FunctionDecl::Create(Context, Parent, Loc, Loc, II, Type,
2208  /*TInfo=*/nullptr, SC_Extern,
2209  getCurFPFeatures().isFPConstrained(),
2210  false, Type->isFunctionProtoType());
2211  New->setImplicit();
2212  New->addAttr(BuiltinAttr::CreateImplicit(Context, ID));
2213 
2214  // Create Decl objects for each parameter, adding them to the
2215  // FunctionDecl.
2216  if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(Type)) {
2218  for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
2220  Context, New, SourceLocation(), SourceLocation(), nullptr,
2221  FT->getParamType(i), /*TInfo=*/nullptr, SC_None, nullptr);
2222  parm->setScopeInfo(0, i);
2223  Params.push_back(parm);
2224  }
2225  New->setParams(Params);
2226  }
2227 
2228  AddKnownFunctionAttributes(New);
2229  return New;
2230 }
2231 
2232 /// LazilyCreateBuiltin - The specified Builtin-ID was first used at
2233 /// file scope. lazily create a decl for it. ForRedeclaration is true
2234 /// if we're creating this built-in in anticipation of redeclaring the
2235 /// built-in.
2237  Scope *S, bool ForRedeclaration,
2238  SourceLocation Loc) {
2239  LookupNecessaryTypesForBuiltin(S, ID);
2240 
2242  QualType R = Context.GetBuiltinType(ID, Error);
2243  if (Error) {
2244  if (!ForRedeclaration)
2245  return nullptr;
2246 
2247  // If we have a builtin without an associated type we should not emit a
2248  // warning when we were not able to find a type for it.
2250  Context.BuiltinInfo.allowTypeMismatch(ID))
2251  return nullptr;
2252 
2253  // If we could not find a type for setjmp it is because the jmp_buf type was
2254  // not defined prior to the setjmp declaration.
2256  Diag(Loc, diag::warn_implicit_decl_no_jmp_buf)
2257  << Context.BuiltinInfo.getName(ID);
2258  return nullptr;
2259  }
2260 
2261  // Generally, we emit a warning that the declaration requires the
2262  // appropriate header.
2263  Diag(Loc, diag::warn_implicit_decl_requires_sysheader)
2264  << getHeaderName(Context.BuiltinInfo, ID, Error)
2265  << Context.BuiltinInfo.getName(ID);
2266  return nullptr;
2267  }
2268 
2269  if (!ForRedeclaration &&
2272  Diag(Loc, diag::ext_implicit_lib_function_decl)
2273  << Context.BuiltinInfo.getName(ID) << R;
2274  if (const char *Header = Context.BuiltinInfo.getHeaderName(ID))
2275  Diag(Loc, diag::note_include_header_or_declare)
2276  << Header << Context.BuiltinInfo.getName(ID);
2277  }
2278 
2279  if (R.isNull())
2280  return nullptr;
2281 
2282  FunctionDecl *New = CreateBuiltin(II, R, ID, Loc);
2283  RegisterLocallyScopedExternCDecl(New, S);
2284 
2285  // TUScope is the translation-unit scope to insert this function into.
2286  // FIXME: This is hideous. We need to teach PushOnScopeChains to
2287  // relate Scopes to DeclContexts, and probably eliminate CurContext
2288  // entirely, but we're not there yet.
2289  DeclContext *SavedContext = CurContext;
2290  CurContext = New->getDeclContext();
2291  PushOnScopeChains(New, TUScope);
2292  CurContext = SavedContext;
2293  return New;
2294 }
2295 
2296 /// Typedef declarations don't have linkage, but they still denote the same
2297 /// entity if their types are the same.
2298 /// FIXME: This is notionally doing the same thing as ASTReaderDecl's
2299 /// isSameEntity.
2303  // This is only interesting when modules are enabled.
2304  if (!S.getLangOpts().Modules && !S.getLangOpts().ModulesLocalVisibility)
2305  return;
2306 
2307  // Empty sets are uninteresting.
2308  if (Previous.empty())
2309  return;
2310 
2311  LookupResult::Filter Filter = Previous.makeFilter();
2312  while (Filter.hasNext()) {
2313  NamedDecl *Old = Filter.next();
2314 
2315  // Non-hidden declarations are never ignored.
2316  if (S.isVisible(Old))
2317  continue;
2318 
2319  // Declarations of the same entity are not ignored, even if they have
2320  // different linkages.
2321  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2322  if (S.Context.hasSameType(OldTD->getUnderlyingType(),
2323  Decl->getUnderlyingType()))
2324  continue;
2325 
2326  // If both declarations give a tag declaration a typedef name for linkage
2327  // purposes, then they declare the same entity.
2328  if (OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true) &&
2329  Decl->getAnonDeclWithTypedefName())
2330  continue;
2331  }
2332 
2333  Filter.erase();
2334  }
2335 
2336  Filter.done();
2337 }
2338 
2340  QualType OldType;
2341  if (TypedefNameDecl *OldTypedef = dyn_cast<TypedefNameDecl>(Old))
2342  OldType = OldTypedef->getUnderlyingType();
2343  else
2344  OldType = Context.getTypeDeclType(Old);
2345  QualType NewType = New->getUnderlyingType();
2346 
2347  if (NewType->isVariablyModifiedType()) {
2348  // Must not redefine a typedef with a variably-modified type.
2349  int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2350  Diag(New->getLocation(), diag::err_redefinition_variably_modified_typedef)
2351  << Kind << NewType;
2352  if (Old->getLocation().isValid())
2353  notePreviousDefinition(Old, New->getLocation());
2354  New->setInvalidDecl();
2355  return true;
2356  }
2357 
2358  if (OldType != NewType &&
2359  !OldType->isDependentType() &&
2360  !NewType->isDependentType() &&
2361  !Context.hasSameType(OldType, NewType)) {
2362  int Kind = isa<TypeAliasDecl>(Old) ? 1 : 0;
2363  Diag(New->getLocation(), diag::err_redefinition_different_typedef)
2364  << Kind << NewType << OldType;
2365  if (Old->getLocation().isValid())
2366  notePreviousDefinition(Old, New->getLocation());
2367  New->setInvalidDecl();
2368  return true;
2369  }
2370  return false;
2371 }
2372 
2373 /// MergeTypedefNameDecl - We just parsed a typedef 'New' which has the
2374 /// same name and scope as a previous declaration 'Old'. Figure out
2375 /// how to resolve this situation, merging decls or emitting
2376 /// diagnostics as appropriate. If there was an error, set New to be invalid.
2377 ///
2379  LookupResult &OldDecls) {
2380  // If the new decl is known invalid already, don't bother doing any
2381  // merging checks.
2382  if (New->isInvalidDecl()) return;
2383 
2384  // Allow multiple definitions for ObjC built-in typedefs.
2385  // FIXME: Verify the underlying types are equivalent!
2386  if (getLangOpts().ObjC) {
2387  const IdentifierInfo *TypeID = New->getIdentifier();
2388  switch (TypeID->getLength()) {
2389  default: break;
2390  case 2:
2391  {
2392  if (!TypeID->isStr("id"))
2393  break;
2394  QualType T = New->getUnderlyingType();
2395  if (!T->isPointerType())
2396  break;
2397  if (!T->isVoidPointerType()) {
2398  QualType PT = T->castAs<PointerType>()->getPointeeType();
2399  if (!PT->isStructureType())
2400  break;
2401  }
2402  Context.setObjCIdRedefinitionType(T);
2403  // Install the built-in type for 'id', ignoring the current definition.
2404  New->setTypeForDecl(Context.getObjCIdType().getTypePtr());
2405  return;
2406  }
2407  case 5:
2408  if (!TypeID->isStr("Class"))
2409  break;
2411  // Install the built-in type for 'Class', ignoring the current definition.
2412  New->setTypeForDecl(Context.getObjCClassType().getTypePtr());
2413  return;
2414  case 3:
2415  if (!TypeID->isStr("SEL"))
2416  break;
2418  // Install the built-in type for 'SEL', ignoring the current definition.
2419  New->setTypeForDecl(Context.getObjCSelType().getTypePtr());
2420  return;
2421  }
2422  // Fall through - the typedef name was not a builtin type.
2423  }
2424 
2425  // Verify the old decl was also a type.
2426  TypeDecl *Old = OldDecls.getAsSingle<TypeDecl>();
2427  if (!Old) {
2428  Diag(New->getLocation(), diag::err_redefinition_different_kind)
2429  << New->getDeclName();
2430 
2431  NamedDecl *OldD = OldDecls.getRepresentativeDecl();
2432  if (OldD->getLocation().isValid())
2433  notePreviousDefinition(OldD, New->getLocation());
2434 
2435  return New->setInvalidDecl();
2436  }
2437 
2438  // If the old declaration is invalid, just give up here.
2439  if (Old->isInvalidDecl())
2440  return New->setInvalidDecl();
2441 
2442  if (auto *OldTD = dyn_cast<TypedefNameDecl>(Old)) {
2443  auto *OldTag = OldTD->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2444  auto *NewTag = New->getAnonDeclWithTypedefName();
2445  NamedDecl *Hidden = nullptr;
2446  if (OldTag && NewTag &&
2447  OldTag->getCanonicalDecl() != NewTag->getCanonicalDecl() &&
2448  !hasVisibleDefinition(OldTag, &Hidden)) {
2449  // There is a definition of this tag, but it is not visible. Use it
2450  // instead of our tag.
2451  New->setTypeForDecl(OldTD->getTypeForDecl());
2452  if (OldTD->isModed())
2453  New->setModedTypeSourceInfo(OldTD->getTypeSourceInfo(),
2454  OldTD->getUnderlyingType());
2455  else
2456  New->setTypeSourceInfo(OldTD->getTypeSourceInfo());
2457 
2458  // Make the old tag definition visible.
2459  makeMergedDefinitionVisible(Hidden);
2460 
2461  // If this was an unscoped enumeration, yank all of its enumerators
2462  // out of the scope.
2463  if (isa<EnumDecl>(NewTag)) {
2464  Scope *EnumScope = getNonFieldDeclScope(S);
2465  for (auto *D : NewTag->decls()) {
2466  auto *ED = cast<EnumConstantDecl>(D);
2467  assert(EnumScope->isDeclScope(ED));
2468  EnumScope->RemoveDecl(ED);
2469  IdResolver.RemoveDecl(ED);
2470  ED->getLexicalDeclContext()->removeDecl(ED);
2471  }
2472  }
2473  }
2474  }
2475 
2476  // If the typedef types are not identical, reject them in all languages and
2477  // with any extensions enabled.
2478  if (isIncompatibleTypedef(Old, New))
2479  return;
2480 
2481  // The types match. Link up the redeclaration chain and merge attributes if
2482  // the old declaration was a typedef.
2483  if (TypedefNameDecl *Typedef = dyn_cast<TypedefNameDecl>(Old)) {
2484  New->setPreviousDecl(Typedef);
2485  mergeDeclAttributes(New, Old);
2486  }
2487 
2488  if (getLangOpts().MicrosoftExt)
2489  return;
2490 
2491  if (getLangOpts().CPlusPlus) {
2492  // C++ [dcl.typedef]p2:
2493  // In a given non-class scope, a typedef specifier can be used to
2494  // redefine the name of any type declared in that scope to refer
2495  // to the type to which it already refers.
2496  if (!isa<CXXRecordDecl>(CurContext))
2497  return;
2498 
2499  // C++0x [dcl.typedef]p4:
2500  // In a given class scope, a typedef specifier can be used to redefine
2501  // any class-name declared in that scope that is not also a typedef-name
2502  // to refer to the type to which it already refers.
2503  //
2504  // This wording came in via DR424, which was a correction to the
2505  // wording in DR56, which accidentally banned code like:
2506  //
2507  // struct S {
2508  // typedef struct A { } A;
2509  // };
2510  //
2511  // in the C++03 standard. We implement the C++0x semantics, which
2512  // allow the above but disallow
2513  //
2514  // struct S {
2515  // typedef int I;
2516  // typedef int I;
2517  // };
2518  //
2519  // since that was the intent of DR56.
2520  if (!isa<TypedefNameDecl>(Old))
2521  return;
2522 
2523  Diag(New->getLocation(), diag::err_redefinition)
2524  << New->getDeclName();
2525  notePreviousDefinition(Old, New->getLocation());
2526  return New->setInvalidDecl();
2527  }
2528 
2529  // Modules always permit redefinition of typedefs, as does C11.
2530  if (getLangOpts().Modules || getLangOpts().C11)
2531  return;
2532 
2533  // If we have a redefinition of a typedef in C, emit a warning. This warning
2534  // is normally mapped to an error, but can be controlled with
2535  // -Wtypedef-redefinition. If either the original or the redefinition is
2536  // in a system header, don't emit this for compatibility with GCC.
2537  if (getDiagnostics().getSuppressSystemWarnings() &&
2538  // Some standard types are defined implicitly in Clang (e.g. OpenCL).
2539  (Old->isImplicit() ||
2540  Context.getSourceManager().isInSystemHeader(Old->getLocation()) ||
2541  Context.getSourceManager().isInSystemHeader(New->getLocation())))
2542  return;
2543 
2544  Diag(New->getLocation(), diag::ext_redefinition_of_typedef)
2545  << New->getDeclName();
2546  notePreviousDefinition(Old, New->getLocation());
2547 }
2548 
2549 /// DeclhasAttr - returns true if decl Declaration already has the target
2550 /// attribute.
2551 static bool DeclHasAttr(const Decl *D, const Attr *A) {
2552  const OwnershipAttr *OA = dyn_cast<OwnershipAttr>(A);
2553  const AnnotateAttr *Ann = dyn_cast<AnnotateAttr>(A);
2554  for (const auto *i : D->attrs())
2555  if (i->getKind() == A->getKind()) {
2556  if (Ann) {
2557  if (Ann->getAnnotation() == cast<AnnotateAttr>(i)->getAnnotation())
2558  return true;
2559  continue;
2560  }
2561  // FIXME: Don't hardcode this check
2562  if (OA && isa<OwnershipAttr>(i))
2563  return OA->getOwnKind() == cast<OwnershipAttr>(i)->getOwnKind();
2564  return true;
2565  }
2566 
2567  return false;
2568 }
2569 
2571  if (VarDecl *VD = dyn_cast<VarDecl>(D))
2572  return VD->isThisDeclarationADefinition();
2573  if (TagDecl *TD = dyn_cast<TagDecl>(D))
2574  return TD->isCompleteDefinition() || TD->isBeingDefined();
2575  return true;
2576 }
2577 
2578 /// Merge alignment attributes from \p Old to \p New, taking into account the
2579 /// special semantics of C11's _Alignas specifier and C++11's alignas attribute.
2580 ///
2581 /// \return \c true if any attributes were added to \p New.
2582 static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old) {
2583  // Look for alignas attributes on Old, and pick out whichever attribute
2584  // specifies the strictest alignment requirement.
2585  AlignedAttr *OldAlignasAttr = nullptr;
2586  AlignedAttr *OldStrictestAlignAttr = nullptr;
2587  unsigned OldAlign = 0;
2588  for (auto *I : Old->specific_attrs<AlignedAttr>()) {
2589  // FIXME: We have no way of representing inherited dependent alignments
2590  // in a case like:
2591  // template<int A, int B> struct alignas(A) X;
2592  // template<int A, int B> struct alignas(B) X {};
2593  // For now, we just ignore any alignas attributes which are not on the
2594  // definition in such a case.
2595  if (I->isAlignmentDependent())
2596  return false;
2597 
2598  if (I->isAlignas())
2599  OldAlignasAttr = I;
2600 
2601  unsigned Align = I->getAlignment(S.Context);
2602  if (Align > OldAlign) {
2603  OldAlign = Align;
2604  OldStrictestAlignAttr = I;
2605  }
2606  }
2607 
2608  // Look for alignas attributes on New.
2609  AlignedAttr *NewAlignasAttr = nullptr;
2610  unsigned NewAlign = 0;
2611  for (auto *I : New->specific_attrs<AlignedAttr>()) {
2612  if (I->isAlignmentDependent())
2613  return false;
2614 
2615  if (I->isAlignas())
2616  NewAlignasAttr = I;
2617 
2618  unsigned Align = I->getAlignment(S.Context);
2619  if (Align > NewAlign)
2620  NewAlign = Align;
2621  }
2622 
2623  if (OldAlignasAttr && NewAlignasAttr && OldAlign != NewAlign) {
2624  // Both declarations have 'alignas' attributes. We require them to match.
2625  // C++11 [dcl.align]p6 and C11 6.7.5/7 both come close to saying this, but
2626  // fall short. (If two declarations both have alignas, they must both match
2627  // every definition, and so must match each other if there is a definition.)
2628 
2629  // If either declaration only contains 'alignas(0)' specifiers, then it
2630  // specifies the natural alignment for the type.
2631  if (OldAlign == 0 || NewAlign == 0) {
2632  QualType Ty;
2633  if (ValueDecl *VD = dyn_cast<ValueDecl>(New))
2634  Ty = VD->getType();
2635  else
2636  Ty = S.Context.getTagDeclType(cast<TagDecl>(New));
2637 
2638  if (OldAlign == 0)
2639  OldAlign = S.Context.getTypeAlign(Ty);
2640  if (NewAlign == 0)
2641  NewAlign = S.Context.getTypeAlign(Ty);
2642  }
2643 
2644  if (OldAlign != NewAlign) {
2645  S.Diag(NewAlignasAttr->getLocation(), diag::err_alignas_mismatch)
2647  << (unsigned)S.Context.toCharUnitsFromBits(NewAlign).getQuantity();
2648  S.Diag(OldAlignasAttr->getLocation(), diag::note_previous_declaration);
2649  }
2650  }
2651 
2652  if (OldAlignasAttr && !NewAlignasAttr && isAttributeTargetADefinition(New)) {
2653  // C++11 [dcl.align]p6:
2654  // if any declaration of an entity has an alignment-specifier,
2655  // every defining declaration of that entity shall specify an
2656  // equivalent alignment.
2657  // C11 6.7.5/7:
2658  // If the definition of an object does not have an alignment
2659  // specifier, any other declaration of that object shall also
2660  // have no alignment specifier.
2661  S.Diag(New->getLocation(), diag::err_alignas_missing_on_definition)
2662  << OldAlignasAttr;
2663  S.Diag(OldAlignasAttr->getLocation(), diag::note_alignas_on_declaration)
2664  << OldAlignasAttr;
2665  }
2666 
2667  bool AnyAdded = false;
2668 
2669  // Ensure we have an attribute representing the strictest alignment.
2670  if (OldAlign > NewAlign) {
2671  AlignedAttr *Clone = OldStrictestAlignAttr->clone(S.Context);
2672  Clone->setInherited(true);
2673  New->addAttr(Clone);
2674  AnyAdded = true;
2675  }
2676 
2677  // Ensure we have an alignas attribute if the old declaration had one.
2678  if (OldAlignasAttr && !NewAlignasAttr &&
2679  !(AnyAdded && OldStrictestAlignAttr->isAlignas())) {
2680  AlignedAttr *Clone = OldAlignasAttr->clone(S.Context);
2681  Clone->setInherited(true);
2682  New->addAttr(Clone);
2683  AnyAdded = true;
2684  }
2685 
2686  return AnyAdded;
2687 }
2688 
2689 #define WANT_DECL_MERGE_LOGIC
2690 #include "clang/Sema/AttrParsedAttrImpl.inc"
2691 #undef WANT_DECL_MERGE_LOGIC
2692 
2693 static bool mergeDeclAttribute(Sema &S, NamedDecl *D,
2694  const InheritableAttr *Attr,
2696  // Diagnose any mutual exclusions between the attribute that we want to add
2697  // and attributes that already exist on the declaration.
2698  if (!DiagnoseMutualExclusions(S, D, Attr))
2699  return false;
2700 
2701  // This function copies an attribute Attr from a previous declaration to the
2702  // new declaration D if the new declaration doesn't itself have that attribute
2703  // yet or if that attribute allows duplicates.
2704  // If you're adding a new attribute that requires logic different from
2705  // "use explicit attribute on decl if present, else use attribute from
2706  // previous decl", for example if the attribute needs to be consistent
2707  // between redeclarations, you need to call a custom merge function here.
2708  InheritableAttr *NewAttr = nullptr;
2709  if (const auto *AA = dyn_cast<AvailabilityAttr>(Attr))
2710  NewAttr = S.mergeAvailabilityAttr(
2711  D, *AA, AA->getPlatform(), AA->isImplicit(), AA->getIntroduced(),
2712  AA->getDeprecated(), AA->getObsoleted(), AA->getUnavailable(),
2713  AA->getMessage(), AA->getStrict(), AA->getReplacement(), AMK,
2714  AA->getPriority());
2715  else if (const auto *VA = dyn_cast<VisibilityAttr>(Attr))
2716  NewAttr = S.mergeVisibilityAttr(D, *VA, VA->getVisibility());
2717  else if (const auto *VA = dyn_cast<TypeVisibilityAttr>(Attr))
2718  NewAttr = S.mergeTypeVisibilityAttr(D, *VA, VA->getVisibility());
2719  else if (const auto *ImportA = dyn_cast<DLLImportAttr>(Attr))
2720  NewAttr = S.mergeDLLImportAttr(D, *ImportA);
2721  else if (const auto *ExportA = dyn_cast<DLLExportAttr>(Attr))
2722  NewAttr = S.mergeDLLExportAttr(D, *ExportA);
2723  else if (const auto *EA = dyn_cast<ErrorAttr>(Attr))
2724  NewAttr = S.mergeErrorAttr(D, *EA, EA->getUserDiagnostic());
2725  else if (const auto *FA = dyn_cast<FormatAttr>(Attr))
2726  NewAttr = S.mergeFormatAttr(D, *FA, FA->getType(), FA->getFormatIdx(),
2727  FA->getFirstArg());
2728  else if (const auto *SA = dyn_cast<SectionAttr>(Attr))
2729  NewAttr = S.mergeSectionAttr(D, *SA, SA->getName());
2730  else if (const auto *CSA = dyn_cast<CodeSegAttr>(Attr))
2731  NewAttr = S.mergeCodeSegAttr(D, *CSA, CSA->getName());
2732  else if (const auto *IA = dyn_cast<MSInheritanceAttr>(Attr))
2733  NewAttr = S.mergeMSInheritanceAttr(D, *IA, IA->getBestCase(),
2734  IA->getInheritanceModel());
2735  else if (const auto *AA = dyn_cast<AlwaysInlineAttr>(Attr))
2736  NewAttr = S.mergeAlwaysInlineAttr(D, *AA,
2737  &S.Context.Idents.get(AA->getSpelling()));
2738  else if (S.getLangOpts().CUDA && isa<FunctionDecl>(D) &&
2739  (isa<CUDAHostAttr>(Attr) || isa<CUDADeviceAttr>(Attr) ||
2740  isa<CUDAGlobalAttr>(Attr))) {
2741  // CUDA target attributes are part of function signature for
2742  // overloading purposes and must not be merged.
2743  return false;
2744  } else if (const auto *MA = dyn_cast<MinSizeAttr>(Attr))
2745  NewAttr = S.mergeMinSizeAttr(D, *MA);
2746  else if (const auto *SNA = dyn_cast<SwiftNameAttr>(Attr))
2747  NewAttr = S.mergeSwiftNameAttr(D, *SNA, SNA->getName());
2748  else if (const auto *OA = dyn_cast<OptimizeNoneAttr>(Attr))
2749  NewAttr = S.mergeOptimizeNoneAttr(D, *OA);
2750  else if (const auto *InternalLinkageA = dyn_cast<InternalLinkageAttr>(Attr))
2751  NewAttr = S.mergeInternalLinkageAttr(D, *InternalLinkageA);
2752  else if (isa<AlignedAttr>(Attr))
2753  // AlignedAttrs are handled separately, because we need to handle all
2754  // such attributes on a declaration at the same time.
2755  NewAttr = nullptr;
2756  else if ((isa<DeprecatedAttr>(Attr) || isa<UnavailableAttr>(Attr)) &&
2757  (AMK == Sema::AMK_Override ||
2760  NewAttr = nullptr;
2761  else if (const auto *UA = dyn_cast<UuidAttr>(Attr))
2762  NewAttr = S.mergeUuidAttr(D, *UA, UA->getGuid(), UA->getGuidDecl());
2763  else if (const auto *IMA = dyn_cast<WebAssemblyImportModuleAttr>(Attr))
2764  NewAttr = S.mergeImportModuleAttr(D, *IMA);
2765  else if (const auto *INA = dyn_cast<WebAssemblyImportNameAttr>(Attr))
2766  NewAttr = S.mergeImportNameAttr(D, *INA);
2767  else if (const auto *A = dyn_cast<SYCLIntelLoopFuseAttr>(Attr))
2768  NewAttr = S.MergeSYCLIntelLoopFuseAttr(D, *A);
2769  else if (const auto *TCBA = dyn_cast<EnforceTCBAttr>(Attr))
2770  NewAttr = S.mergeEnforceTCBAttr(D, *TCBA);
2771  else if (const auto *TCBLA = dyn_cast<EnforceTCBLeafAttr>(Attr))
2772  NewAttr = S.mergeEnforceTCBLeafAttr(D, *TCBLA);
2773  else if (const auto *A = dyn_cast<IntelReqdSubGroupSizeAttr>(Attr))
2774  NewAttr = S.MergeIntelReqdSubGroupSizeAttr(D, *A);
2775  else if (const auto *A = dyn_cast<IntelNamedSubGroupSizeAttr>(Attr))
2776  NewAttr = S.MergeIntelNamedSubGroupSizeAttr(D, *A);
2777  else if (const auto *A = dyn_cast<SYCLIntelNumSimdWorkItemsAttr>(Attr))
2778  NewAttr = S.MergeSYCLIntelNumSimdWorkItemsAttr(D, *A);
2779  else if (const auto *A = dyn_cast<SYCLIntelESimdVectorizeAttr>(Attr))
2780  NewAttr = S.MergeSYCLIntelESimdVectorizeAttr(D, *A);
2781  else if (const auto *A = dyn_cast<SYCLIntelSchedulerTargetFmaxMhzAttr>(Attr))
2782  NewAttr = S.MergeSYCLIntelSchedulerTargetFmaxMhzAttr(D, *A);
2783  else if (const auto *A = dyn_cast<SYCLIntelNoGlobalWorkOffsetAttr>(Attr))
2784  NewAttr = S.MergeSYCLIntelNoGlobalWorkOffsetAttr(D, *A);
2785  else if (const auto *A = dyn_cast<IntelFPGAMaxReplicatesAttr>(Attr))
2786  NewAttr = S.MergeIntelFPGAMaxReplicatesAttr(D, *A);
2787  else if (const auto *A = dyn_cast<SYCLIntelFPGAMaxConcurrencyAttr>(Attr))
2788  NewAttr = S.MergeSYCLIntelFPGAMaxConcurrencyAttr(D, *A);
2789  else if (const auto *A = dyn_cast<IntelFPGAForcePow2DepthAttr>(Attr))
2790  NewAttr = S.MergeIntelFPGAForcePow2DepthAttr(D, *A);
2791  else if (const auto *A = dyn_cast<SYCLIntelFPGAInitiationIntervalAttr>(Attr))
2792  NewAttr = S.MergeSYCLIntelFPGAInitiationIntervalAttr(D, *A);
2793  else if (const auto *A = dyn_cast<WorkGroupSizeHintAttr>(Attr))
2794  NewAttr = S.MergeWorkGroupSizeHintAttr(D, *A);
2795  else if (const auto *A = dyn_cast<SYCLIntelMaxGlobalWorkDimAttr>(Attr))
2796  NewAttr = S.MergeSYCLIntelMaxGlobalWorkDimAttr(D, *A);
2797  else if (const auto *BTFA = dyn_cast<BTFDeclTagAttr>(Attr))
2798  NewAttr = S.mergeBTFDeclTagAttr(D, *BTFA);
2799  else if (const auto *A = dyn_cast<IntelFPGABankWidthAttr>(Attr))
2800  NewAttr = S.MergeIntelFPGABankWidthAttr(D, *A);
2801  else if (const auto *A = dyn_cast<IntelFPGANumBanksAttr>(Attr))
2802  NewAttr = S.MergeIntelFPGANumBanksAttr(D, *A);
2803  else if (const auto *A = dyn_cast<SYCLDeviceHasAttr>(Attr))
2804  NewAttr = S.MergeSYCLDeviceHasAttr(D, *A);
2805  else if (const auto *A = dyn_cast<SYCLUsesAspectsAttr>(Attr))
2806  NewAttr = S.MergeSYCLUsesAspectsAttr(D, *A);
2807  else if (const auto *A = dyn_cast<SYCLIntelPipeIOAttr>(Attr))
2808  NewAttr = S.MergeSYCLIntelPipeIOAttr(D, *A);
2809  else if (const auto *A = dyn_cast<SYCLIntelMaxWorkGroupSizeAttr>(Attr))
2810  NewAttr = S.MergeSYCLIntelMaxWorkGroupSizeAttr(D, *A);
2811  else if (const auto *A = dyn_cast<SYCLAddIRAttributesFunctionAttr>(Attr))
2812  NewAttr = S.MergeSYCLAddIRAttributesFunctionAttr(D, *A);
2813  else if (const auto *A =
2814  dyn_cast<SYCLAddIRAttributesKernelParameterAttr>(Attr))
2816  else if (const auto *A =
2817  dyn_cast<SYCLAddIRAttributesGlobalVariableAttr>(Attr))
2818  NewAttr = S.MergeSYCLAddIRAttributesGlobalVariableAttr(D, *A);
2819  else if (const auto *A = dyn_cast<ReqdWorkGroupSizeAttr>(Attr))
2820  NewAttr = S.MergeReqdWorkGroupSizeAttr(D, *A);
2821  else if (Attr->shouldInheritEvenIfAlreadyPresent() || !DeclHasAttr(D, Attr))
2822  NewAttr = cast<InheritableAttr>(Attr->clone(S.Context));
2823 
2824  if (NewAttr) {
2825  NewAttr->setInherited(true);
2826  D->addAttr(NewAttr);
2827  if (isa<MSInheritanceAttr>(NewAttr))
2828  S.Consumer.AssignInheritanceModel(cast<CXXRecordDecl>(D));
2829  return true;
2830  }
2831 
2832  return false;
2833 }
2834 
2835 static const NamedDecl *getDefinition(const Decl *D) {
2836  if (const TagDecl *TD = dyn_cast<TagDecl>(D))
2837  return TD->getDefinition();
2838  if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
2839  const VarDecl *Def = VD->getDefinition();
2840  if (Def)
2841  return Def;
2842  return VD->getActingDefinition();
2843  }
2844  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2845  const FunctionDecl *Def = nullptr;
2846  if (FD->isDefined(Def, true))
2847  return Def;
2848  }
2849  return nullptr;
2850 }
2851 
2852 static bool hasAttribute(const Decl *D, attr::Kind Kind) {
2853  for (const auto *Attribute : D->attrs())
2854  if (Attribute->getKind() == Kind)
2855  return true;
2856  return false;
2857 }
2858 
2859 /// checkNewAttributesAfterDef - If we already have a definition, check that
2860 /// there are no new attributes in this declaration.
2861 static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old) {
2862  if (!New->hasAttrs())
2863  return;
2864 
2865  const NamedDecl *Def = getDefinition(Old);
2866  if (!Def || Def == New)
2867  return;
2868 
2869  AttrVec &NewAttributes = New->getAttrs();
2870  for (unsigned I = 0, E = NewAttributes.size(); I != E;) {
2871  const Attr *NewAttribute = NewAttributes[I];
2872 
2873  if (isa<AliasAttr>(NewAttribute) || isa<IFuncAttr>(NewAttribute)) {
2874  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(New)) {
2875  Sema::SkipBodyInfo SkipBody;
2876  S.CheckForFunctionRedefinition(FD, cast<FunctionDecl>(Def), &SkipBody);
2877 
2878  // If we're skipping this definition, drop the "alias" attribute.
2879  if (SkipBody.ShouldSkip) {
2880  NewAttributes.erase(NewAttributes.begin() + I);
2881  --E;
2882  continue;
2883  }
2884  } else {
2885  VarDecl *VD = cast<VarDecl>(New);
2886  unsigned Diag = cast<VarDecl>(Def)->isThisDeclarationADefinition() ==
2888  ? diag::err_alias_after_tentative
2889  : diag::err_redefinition;
2890  S.Diag(VD->getLocation(), Diag) << VD->getDeclName();
2891  if (Diag == diag::err_redefinition)
2892  S.notePreviousDefinition(Def, VD->getLocation());
2893  else
2894  S.Diag(Def->getLocation(), diag::note_previous_definition);
2895  VD->setInvalidDecl();
2896  }
2897  ++I;
2898  continue;
2899  }
2900 
2901  if (const VarDecl *VD = dyn_cast<VarDecl>(Def)) {
2902  // Tentative definitions are only interesting for the alias check above.
2903  if (VD->isThisDeclarationADefinition() != VarDecl::Definition) {
2904  ++I;
2905  continue;
2906  }
2907  }
2908 
2909  if (hasAttribute(Def, NewAttribute->getKind())) {
2910  ++I;
2911  continue; // regular attr merging will take care of validating this.
2912  }
2913 
2914  if (isa<C11NoReturnAttr>(NewAttribute)) {
2915  // C's _Noreturn is allowed to be added to a function after it is defined.
2916  ++I;
2917  continue;
2918  } else if (isa<UuidAttr>(NewAttribute)) {
2919  // msvc will allow a subsequent definition to add an uuid to a class
2920  ++I;
2921  continue;
2922  } else if (const AlignedAttr *AA = dyn_cast<AlignedAttr>(NewAttribute)) {
2923  if (AA->isAlignas()) {
2924  // C++11 [dcl.align]p6:
2925  // if any declaration of an entity has an alignment-specifier,
2926  // every defining declaration of that entity shall specify an
2927  // equivalent alignment.
2928  // C11 6.7.5/7:
2929  // If the definition of an object does not have an alignment
2930  // specifier, any other declaration of that object shall also
2931  // have no alignment specifier.
2932  S.Diag(Def->getLocation(), diag::err_alignas_missing_on_definition)
2933  << AA;
2934  S.Diag(NewAttribute->getLocation(), diag::note_alignas_on_declaration)
2935  << AA;
2936  NewAttributes.erase(NewAttributes.begin() + I);
2937  --E;
2938  continue;
2939  }
2940  } else if (isa<LoaderUninitializedAttr>(NewAttribute)) {
2941  // If there is a C definition followed by a redeclaration with this
2942  // attribute then there are two different definitions. In C++, prefer the
2943  // standard diagnostics.
2944  if (!S.getLangOpts().CPlusPlus) {
2945  S.Diag(NewAttribute->getLocation(),
2946  diag::err_loader_uninitialized_redeclaration);
2947  S.Diag(Def->getLocation(), diag::note_previous_definition);
2948  NewAttributes.erase(NewAttributes.begin() + I);
2949  --E;
2950  continue;
2951  }
2952  } else if (isa<SelectAnyAttr>(NewAttribute) &&
2953  cast<VarDecl>(New)->isInline() &&
2954  !cast<VarDecl>(New)->isInlineSpecified()) {
2955  // Don't warn about applying selectany to implicitly inline variables.
2956  // Older compilers and language modes would require the use of selectany
2957  // to make such variables inline, and it would have no effect if we
2958  // honored it.
2959  ++I;
2960  continue;
2961  } else if (isa<OMPDeclareVariantAttr>(NewAttribute)) {
2962  // We allow to add OMP[Begin]DeclareVariantAttr to be added to
2963  // declarations after defintions.
2964  ++I;
2965  continue;
2966  }
2967 
2968  S.Diag(NewAttribute->getLocation(),
2969  diag::warn_attribute_precede_definition);
2970  S.Diag(Def->getLocation(), diag::note_previous_definition);
2971  NewAttributes.erase(NewAttributes.begin() + I);
2972  --E;
2973  }
2974 }
2975 
2976 static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl,
2977  const ConstInitAttr *CIAttr,
2978  bool AttrBeforeInit) {
2979  SourceLocation InsertLoc = InitDecl->getInnerLocStart();
2980 
2981  // Figure out a good way to write this specifier on the old declaration.
2982  // FIXME: We should just use the spelling of CIAttr, but we don't preserve
2983  // enough of the attribute list spelling information to extract that without
2984  // heroics.
2985  std::string SuitableSpelling;
2986  if (S.getLangOpts().CPlusPlus20)
2987  SuitableSpelling = std::string(
2988  S.PP.getLastMacroWithSpelling(InsertLoc, {tok::kw_constinit}));
2989  if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
2990  SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2991  InsertLoc, {tok::l_square, tok::l_square,
2992  S.PP.getIdentifierInfo("clang"), tok::coloncolon,
2993  S.PP.getIdentifierInfo("require_constant_initialization"),
2994  tok::r_square, tok::r_square}));
2995  if (SuitableSpelling.empty())
2996  SuitableSpelling = std::string(S.PP.getLastMacroWithSpelling(
2997  InsertLoc, {tok::kw___attribute, tok::l_paren, tok::r_paren,
2998  S.PP.getIdentifierInfo("require_constant_initialization"),
2999  tok::r_paren, tok::r_paren}));
3000  if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus20)
3001  SuitableSpelling = "constinit";
3002  if (SuitableSpelling.empty() && S.getLangOpts().CPlusPlus11)
3003  SuitableSpelling = "[[clang::require_constant_initialization]]";
3004  if (SuitableSpelling.empty())
3005  SuitableSpelling = "__attribute__((require_constant_initialization))";
3006  SuitableSpelling += " ";
3007 
3008  if (AttrBeforeInit) {
3009  // extern constinit int a;
3010  // int a = 0; // error (missing 'constinit'), accepted as extension
3011  assert(CIAttr->isConstinit() && "should not diagnose this for attribute");
3012  S.Diag(InitDecl->getLocation(), diag::ext_constinit_missing)
3013  << InitDecl << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3014  S.Diag(CIAttr->getLocation(), diag::note_constinit_specified_here);
3015  } else {
3016  // int a = 0;
3017  // constinit extern int a; // error (missing 'constinit')
3018  S.Diag(CIAttr->getLocation(),
3019  CIAttr->isConstinit() ? diag::err_constinit_added_too_late
3020  : diag::warn_require_const_init_added_too_late)
3021  << FixItHint::CreateRemoval(SourceRange(CIAttr->getLocation()));
3022  S.Diag(InitDecl->getLocation(), diag::note_constinit_missing_here)
3023  << CIAttr->isConstinit()
3024  << FixItHint::CreateInsertion(InsertLoc, SuitableSpelling);
3025  }
3026 }
3027 
3028 /// mergeDeclAttributes - Copy attributes from the Old decl to the New one.
3030  AvailabilityMergeKind AMK) {
3031  if (UsedAttr *OldAttr = Old->getMostRecentDecl()->getAttr<UsedAttr>()) {
3032  UsedAttr *NewAttr = OldAttr->clone(Context);
3033  NewAttr->setInherited(true);
3034  New->addAttr(NewAttr);
3035  }
3036  if (RetainAttr *OldAttr = Old->getMostRecentDecl()->getAttr<RetainAttr>()) {
3037  RetainAttr *NewAttr = OldAttr->clone(Context);
3038  NewAttr->setInherited(true);
3039  New->addAttr(NewAttr);
3040  }
3041 
3042  if (!Old->hasAttrs() && !New->hasAttrs())
3043  return;
3044 
3045  // [dcl.constinit]p1:
3046  // If the [constinit] specifier is applied to any declaration of a
3047  // variable, it shall be applied to the initializing declaration.
3048  const auto *OldConstInit = Old->getAttr<ConstInitAttr>();
3049  const auto *NewConstInit = New->getAttr<ConstInitAttr>();
3050  if (bool(OldConstInit) != bool(NewConstInit)) {
3051  const auto *OldVD = cast<VarDecl>(Old);
3052  auto *NewVD = cast<VarDecl>(New);
3053 
3054  // Find the initializing declaration. Note that we might not have linked
3055  // the new declaration into the redeclaration chain yet.
3056  const VarDecl *InitDecl = OldVD->getInitializingDeclaration();
3057  if (!InitDecl &&
3058  (NewVD->hasInit() || NewVD->isThisDeclarationADefinition()))
3059  InitDecl = NewVD;
3060 
3061  if (InitDecl == NewVD) {
3062  // This is the initializing declaration. If it would inherit 'constinit',
3063  // that's ill-formed. (Note that we do not apply this to the attribute
3064  // form).
3065  if (OldConstInit && OldConstInit->isConstinit())
3066  diagnoseMissingConstinit(*this, NewVD, OldConstInit,
3067  /*AttrBeforeInit=*/true);
3068  } else if (NewConstInit) {
3069  // This is the first time we've been told that this declaration should
3070  // have a constant initializer. If we already saw the initializing
3071  // declaration, this is too late.
3072  if (InitDecl && InitDecl != NewVD) {
3073  diagnoseMissingConstinit(*this, InitDecl, NewConstInit,
3074  /*AttrBeforeInit=*/false);
3075  NewVD->dropAttr<ConstInitAttr>();
3076  }
3077  }
3078  }
3079 
3080  // Attributes declared post-definition are currently ignored.
3081  checkNewAttributesAfterDef(*this, New, Old);
3082 
3083  if (AsmLabelAttr *NewA = New->getAttr<AsmLabelAttr>()) {
3084  if (AsmLabelAttr *OldA = Old->getAttr<AsmLabelAttr>()) {
3085  if (!OldA->isEquivalent(NewA)) {
3086  // This redeclaration changes __asm__ label.
3087  Diag(New->getLocation(), diag::err_different_asm_label);
3088  Diag(OldA->getLocation(), diag::note_previous_declaration);
3089  }
3090  } else if (Old->isUsed()) {
3091  // This redeclaration adds an __asm__ label to a declaration that has
3092  // already been ODR-used.
3093  Diag(New->getLocation(), diag::err_late_asm_label_name)
3094  << isa<FunctionDecl>(Old) << New->getAttr<AsmLabelAttr>()->getRange();
3095  }
3096  }
3097 
3098  // Re-declaration cannot add abi_tag's.
3099  if (const auto *NewAbiTagAttr = New->getAttr<AbiTagAttr>()) {
3100  if (const auto *OldAbiTagAttr = Old->getAttr<AbiTagAttr>()) {
3101  for (const auto &NewTag : NewAbiTagAttr->tags()) {
3102  if (!llvm::is_contained(OldAbiTagAttr->tags(), NewTag)) {
3103  Diag(NewAbiTagAttr->getLocation(),
3104  diag::err_new_abi_tag_on_redeclaration)
3105  << NewTag;
3106  Diag(OldAbiTagAttr->getLocation(), diag::note_previous_declaration);
3107  }
3108  }
3109  } else {
3110  Diag(NewAbiTagAttr->getLocation(), diag::err_abi_tag_on_redeclaration);
3111  Diag(Old->getLocation(), diag::note_previous_declaration);
3112  }
3113  }
3114 
3115  // This redeclaration adds a section attribute.
3116  if (New->hasAttr<SectionAttr>() && !Old->hasAttr<SectionAttr>()) {
3117  if (auto *VD = dyn_cast<VarDecl>(New)) {
3118  if (VD->isThisDeclarationADefinition() == VarDecl::DeclarationOnly) {
3119  Diag(New->getLocation(), diag::warn_attribute_section_on_redeclaration);
3120  Diag(Old->getLocation(), diag::note_previous_declaration);
3121  }
3122  }
3123  }
3124 
3125  // Redeclaration adds code-seg attribute.
3126  const auto *NewCSA = New->getAttr<CodeSegAttr>();
3127  if (NewCSA && !Old->hasAttr<CodeSegAttr>() &&
3128  !NewCSA->isImplicit() && isa<CXXMethodDecl>(New)) {
3129  Diag(New->getLocation(), diag::warn_mismatched_section)
3130  << 0 /*codeseg*/;
3131  Diag(Old->getLocation(), diag::note_previous_declaration);
3132  }
3133 
3134  if (!Old->hasAttrs())
3135  return;
3136 
3137  bool foundAny = New->hasAttrs();
3138 
3139  // Ensure that any moving of objects within the allocated map is done before
3140  // we process them.
3141  if (!foundAny) New->setAttrs(AttrVec());
3142 
3143  for (auto *I : Old->specific_attrs<InheritableAttr>()) {
3144  // Ignore deprecated/unavailable/availability attributes if requested.
3145  AvailabilityMergeKind LocalAMK = AMK_None;
3146  if (isa<DeprecatedAttr>(I) ||
3147  isa<UnavailableAttr>(I) ||
3148  isa<AvailabilityAttr>(I)) {
3149  switch (AMK) {
3150  case AMK_None:
3151  continue;
3152 
3153  case AMK_Redeclaration:
3154  case AMK_Override:
3155  case AMK_ProtocolImplementation:
3156  case AMK_OptionalProtocolImplementation:
3157  LocalAMK = AMK;
3158  break;
3159  }
3160  }
3161 
3162  // Already handled.
3163  if (isa<UsedAttr>(I) || isa<RetainAttr>(I))
3164  continue;
3165 
3166  if (mergeDeclAttribute(*this, New, I, LocalAMK))
3167  foundAny = true;
3168  }
3169 
3170  if (mergeAlignedAttrs(*this, New, Old))
3171  foundAny = true;
3172 
3173  if (!foundAny) New->dropAttrs();
3174 }
3175 
3176 /// mergeParamDeclAttributes - Copy attributes from the old parameter
3177 /// to the new one.
3179  const ParmVarDecl *oldDecl,
3180  Sema &S) {
3181  // C++11 [dcl.attr.depend]p2:
3182  // The first declaration of a function shall specify the
3183  // carries_dependency attribute for its declarator-id if any declaration
3184  // of the function specifies the carries_dependency attribute.
3185  const CarriesDependencyAttr *CDA = newDecl->getAttr<CarriesDependencyAttr>();
3186  if (CDA && !oldDecl->hasAttr<CarriesDependencyAttr>()) {
3187  S.Diag(CDA->getLocation(),
3188  diag::err_carries_dependency_missing_on_first_decl) << 1/*Param*/;
3189  // Find the first declaration of the parameter.
3190  // FIXME: Should we build redeclaration chains for function parameters?
3191  const FunctionDecl *FirstFD =
3192  cast<FunctionDecl>(oldDecl->getDeclContext())->getFirstDecl();
3193  const ParmVarDecl *FirstVD =
3194  FirstFD->getParamDecl(oldDecl->getFunctionScopeIndex());
3195  S.Diag(FirstVD->getLocation(),
3196  diag::note_carries_dependency_missing_first_decl) << 1/*Param*/;
3197  }
3198 
3199  if (!oldDecl->hasAttrs())
3200  return;
3201 
3202  bool foundAny = newDecl->hasAttrs();
3203 
3204  // Ensure that any moving of objects within the allocated map is
3205  // done before we process them.
3206  if (!foundAny) newDecl->setAttrs(AttrVec());
3207 
3208  for (const auto *I : oldDecl->specific_attrs<InheritableParamAttr>()) {
3209  if (!DeclHasAttr(newDecl, I)) {
3210  InheritableAttr *newAttr =
3211  cast<InheritableParamAttr>(I->clone(S.Context));
3212  newAttr->setInherited(true);
3213  newDecl->addAttr(newAttr);
3214  foundAny = true;
3215  }
3216  }
3217 
3218  if (!foundAny) newDecl->dropAttrs();
3219 }
3220 
3221 static void mergeParamDeclTypes(ParmVarDecl *NewParam,
3222  const ParmVarDecl *OldParam,
3223  Sema &S) {
3224  if (auto Oldnullability = OldParam->getType()->getNullability(S.Context)) {
3225  if (auto Newnullability = NewParam->getType()->getNullability(S.Context)) {
3226  if (*Oldnullability != *Newnullability) {
3227  S.Diag(NewParam->getLocation(), diag::warn_mismatched_nullability_attr)
3229  *Newnullability,
3231  != 0))
3233  *Oldnullability,
3235  != 0));
3236  S.Diag(OldParam->getLocation(), diag::note_previous_declaration);
3237  }
3238  } else {
3239  QualType NewT = NewParam->getType();
3240  NewT = S.Context.getAttributedType(
3241  AttributedType::getNullabilityAttrKind(*Oldnullability),
3242  NewT, NewT);
3243  NewParam->setType(NewT);
3244  }
3245  }
3246 }
3247 
3248 namespace {
3249 
3250 /// Used in MergeFunctionDecl to keep track of function parameters in
3251 /// C.
3252 struct GNUCompatibleParamWarning {
3253  ParmVarDecl *OldParm;
3254  ParmVarDecl *NewParm;
3255  QualType PromotedType;
3256 };
3257 
3258 } // end anonymous namespace
3259 
3260 // Determine whether the previous declaration was a definition, implicit
3261 // declaration, or a declaration.
3262 template <typename T>
3263 static std::pair<diag::kind, SourceLocation>
3264 getNoteDiagForInvalidRedeclaration(const T *Old, const T *New) {
3265  diag::kind PrevDiag;
3266  SourceLocation OldLocation = Old->getLocation();
3267  if (Old->isThisDeclarationADefinition())
3268  PrevDiag = diag::note_previous_definition;
3269  else if (Old->isImplicit()) {
3270  PrevDiag = diag::note_previous_implicit_declaration;
3271  if (OldLocation.isInvalid())
3272  OldLocation = New->getLocation();
3273  } else
3274  PrevDiag = diag::note_previous_declaration;
3275  return std::make_pair(PrevDiag, OldLocation);
3276 }
3277 
3278 /// canRedefineFunction - checks if a function can be redefined. Currently,
3279 /// only extern inline functions can be redefined, and even then only in
3280 /// GNU89 mode.
3281 static bool canRedefineFunction(const FunctionDecl *FD,
3282  const LangOptions& LangOpts) {
3283  return ((FD->hasAttr<GNUInlineAttr>() || LangOpts.GNUInline) &&
3284  !LangOpts.CPlusPlus &&
3285  FD->isInlineSpecified() &&
3286  FD->getStorageClass() == SC_Extern);
3287 }
3288 
3290  const AttributedType *AT = T->getAs<AttributedType>();
3291  while (AT && !AT->isCallingConv())
3292  AT = AT->getModifiedType()->getAs<AttributedType>();
3293  return AT;
3294 }
3295 
3296 template <typename T>
3297 static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New) {
3298  const DeclContext *DC = Old->getDeclContext();
3299  if (DC->isRecord())
3300  return false;
3301 
3302  LanguageLinkage OldLinkage = Old->getLanguageLinkage();
3303  if (OldLinkage == CXXLanguageLinkage && New->isInExternCContext())
3304  return true;
3305  if (OldLinkage == CLanguageLinkage && New->isInExternCXXContext())
3306  return true;
3307  return false;
3308 }
3309 
3310 template<typename T> static bool isExternC(T *D) { return D->isExternC(); }
3311 static bool isExternC(VarTemplateDecl *) { return false; }
3312 static bool isExternC(FunctionTemplateDecl *) { return false; }
3313 
3314 /// Check whether a redeclaration of an entity introduced by a
3315 /// using-declaration is valid, given that we know it's not an overload
3316 /// (nor a hidden tag declaration).
3317 template<typename ExpectedDecl>
3319  ExpectedDecl *New) {
3320  // C++11 [basic.scope.declarative]p4:
3321  // Given a set of declarations in a single declarative region, each of
3322  // which specifies the same unqualified name,
3323  // -- they shall all refer to the same entity, or all refer to functions
3324  // and function templates; or
3325  // -- exactly one declaration shall declare a class name or enumeration
3326  // name that is not a typedef name and the other declarations shall all
3327  // refer to the same variable or enumerator, or all refer to functions
3328  // and function templates; in this case the class name or enumeration
3329  // name is hidden (3.3.10).
3330 
3331  // C++11 [namespace.udecl]p14:
3332  // If a function declaration in namespace scope or block scope has the
3333  // same name and the same parameter-type-list as a function introduced
3334  // by a using-declaration, and the declarations do not declare the same
3335  // function, the program is ill-formed.
3336 
3337  auto *Old = dyn_cast<ExpectedDecl>(OldS->getTargetDecl());
3338  if (Old &&
3339  !Old->getDeclContext()->getRedeclContext()->Equals(
3340  New->getDeclContext()->getRedeclContext()) &&
3341  !(isExternC(Old) && isExternC(New)))
3342  Old = nullptr;
3343 
3344  if (!Old) {
3345  S.Diag(New->getLocation(), diag::err_using_decl_conflict_reverse);
3346  S.Diag(OldS->getTargetDecl()->getLocation(), diag::note_using_decl_target);
3347  S.Diag(OldS->getIntroducer()->getLocation(), diag::note_using_decl) << 0;
3348  return true;
3349  }
3350  return false;
3351 }
3352 
3354  const FunctionDecl *B) {
3355  assert(A->getNumParams() == B->getNumParams());
3356 
3357  auto AttrEq = [](const ParmVarDecl *A, const ParmVarDecl *B) {
3358  const auto *AttrA = A->getAttr<PassObjectSizeAttr>();
3359  const auto *AttrB = B->getAttr<PassObjectSizeAttr>();
3360  if (AttrA == AttrB)
3361  return true;
3362  return AttrA && AttrB && AttrA->getType() == AttrB->getType() &&
3363  AttrA->isDynamic() == AttrB->isDynamic();
3364  };
3365 
3366  return std::equal(A->param_begin(), A->param_end(), B->param_begin(), AttrEq);
3367 }
3368 
3369 /// If necessary, adjust the semantic declaration context for a qualified
3370 /// declaration to name the correct inline namespace within the qualifier.
3372  DeclaratorDecl *OldD) {
3373  // The only case where we need to update the DeclContext is when
3374  // redeclaration lookup for a qualified name finds a declaration
3375  // in an inline namespace within the context named by the qualifier:
3376  //
3377  // inline namespace N { int f(); }
3378  // int ::f(); // Sema DC needs adjusting from :: to N::.
3379  //
3380  // For unqualified declarations, the semantic context *can* change
3381  // along the redeclaration chain (for local extern declarations,
3382  // extern "C" declarations, and friend declarations in particular).
3383  if (!NewD->getQualifier())
3384  return;
3385 
3386  // NewD is probably already in the right context.
3387  auto *NamedDC = NewD->getDeclContext()->getRedeclContext();
3388  auto *SemaDC = OldD->getDeclContext()->getRedeclContext();
3389  if (NamedDC->Equals(SemaDC))
3390  return;
3391 
3392  assert((NamedDC->InEnclosingNamespaceSetOf(SemaDC) ||
3393  NewD->isInvalidDecl() || OldD->isInvalidDecl()) &&
3394  "unexpected context for redeclaration");
3395 
3396  auto *LexDC = NewD->getLexicalDeclContext();
3397  auto FixSemaDC = [=](NamedDecl *D) {
3398  if (!D)
3399  return;
3400  D->setDeclContext(SemaDC);
3401  D->setLexicalDeclContext(LexDC);
3402  };
3403 
3404  FixSemaDC(NewD);
3405  if (auto *FD = dyn_cast<FunctionDecl>(NewD))
3406  FixSemaDC(FD->getDescribedFunctionTemplate());
3407  else if (auto *VD = dyn_cast<VarDecl>(NewD))
3408  FixSemaDC(VD->getDescribedVarTemplate());
3409 }
3410 
3411 /// MergeFunctionDecl - We just parsed a function 'New' from
3412 /// declarator D which has the same name and scope as a previous
3413 /// declaration 'Old'. Figure out how to resolve this situation,
3414 /// merging decls or emitting diagnostics as appropriate.
3415 ///
3416 /// In C++, New and Old must be declarations that are not
3417 /// overloaded. Use IsOverload to determine whether New and Old are
3418 /// overloaded, and to select the Old declaration that New should be
3419 /// merged with.
3420 ///
3421 /// Returns true if there was an error, false otherwise.
3423  Scope *S, bool MergeTypeWithOld) {
3424  // Verify the old decl was also a function.
3425  FunctionDecl *Old = OldD->getAsFunction();
3426  if (!Old) {
3427  if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(OldD)) {
3428  if (New->getFriendObjectKind()) {
3429  Diag(New->getLocation(), diag::err_using_decl_friend);
3430  Diag(Shadow->getTargetDecl()->getLocation(),
3431  diag::note_using_decl_target);
3432  Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
3433  << 0;
3434  return true;
3435  }
3436 
3437  // Check whether the two declarations might declare the same function or
3438  // function template.
3439  if (FunctionTemplateDecl *NewTemplate =
3441  if (checkUsingShadowRedecl<FunctionTemplateDecl>(*this, Shadow,
3442  NewTemplate))
3443  return true;
3444  OldD = Old = cast<FunctionTemplateDecl>(Shadow->getTargetDecl())
3445  ->getAsFunction();
3446  } else {
3447  if (checkUsingShadowRedecl<FunctionDecl>(*this, Shadow, New))
3448  return true;
3449  OldD = Old = cast<FunctionDecl>(Shadow->getTargetDecl());
3450  }
3451  } else {
3452  Diag(New->getLocation(), diag::err_redefinition_different_kind)
3453  << New->getDeclName();
3454  notePreviousDefinition(OldD, New->getLocation());
3455  return true;
3456  }
3457  }
3458 
3459  // If the old declaration was found in an inline namespace and the new
3460  // declaration was qualified, update the DeclContext to match.
3462 
3463  // If the old declaration is invalid, just give up here.
3464  if (Old->isInvalidDecl())
3465  return true;
3466 
3467  // Disallow redeclaration of some builtins.
3468  if (!getASTContext().canBuiltinBeRedeclared(Old)) {
3469  Diag(New->getLocation(), diag::err_builtin_redeclare) << Old->getDeclName();
3470  Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
3471  << Old << Old->getType();
3472  return true;
3473  }
3474 
3475  diag::kind PrevDiag;
3476  SourceLocation OldLocation;
3477  std::tie(PrevDiag, OldLocation) =
3479 
3480  // Don't complain about this if we're in GNU89 mode and the old function
3481  // is an extern inline function.
3482  // Don't complain about specializations. They are not supposed to have
3483  // storage classes.
3484  if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
3485  New->getStorageClass() == SC_Static &&
3486  Old->hasExternalFormalLinkage() &&
3488  !canRedefineFunction(Old, getLangOpts())) {
3489  if (getLangOpts().MicrosoftExt) {
3490  Diag(New->getLocation(), diag::ext_static_non_static) << New;
3491  Diag(OldLocation, PrevDiag);
3492  } else {
3493  Diag(New->getLocation(), diag::err_static_non_static) << New;
3494  Diag(OldLocation, PrevDiag);
3495  return true;
3496  }
3497  }
3498 
3499  if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
3500  if (!Old->hasAttr<InternalLinkageAttr>()) {
3501  Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
3502  << ILA;
3503  Diag(Old->getLocation(), diag::note_previous_declaration);
3504  New->dropAttr<InternalLinkageAttr>();
3505  }
3506 
3507  if (auto *EA = New->getAttr<ErrorAttr>()) {
3508  if (!Old->hasAttr<ErrorAttr>()) {
3509  Diag(EA->getLocation(), diag::err_attribute_missing_on_first_decl) << EA;
3510  Diag(Old->getLocation(), diag::note_previous_declaration);
3511  New->dropAttr<ErrorAttr>();
3512  }
3513  }
3514 
3515  if (CheckRedeclarationInModule(New, Old))
3516  return true;
3517 
3518  if (!getLangOpts().CPlusPlus) {
3519  bool OldOvl = Old->hasAttr<OverloadableAttr>();
3520  if (OldOvl != New->hasAttr<OverloadableAttr>() && !Old->isImplicit()) {
3521  Diag(New->getLocation(), diag::err_attribute_overloadable_mismatch)
3522  << New << OldOvl;
3523 
3524  // Try our best to find a decl that actually has the overloadable
3525  // attribute for the note. In most cases (e.g. programs with only one
3526  // broken declaration/definition), this won't matter.
3527  //
3528  // FIXME: We could do this if we juggled some extra state in
3529  // OverloadableAttr, rather than just removing it.
3530  const Decl *DiagOld = Old;
3531  if (OldOvl) {
3532  auto OldIter = llvm::find_if(Old->redecls(), [](const Decl *D) {
3533  const auto *A = D->getAttr<OverloadableAttr>();
3534  return A && !A->isImplicit();
3535  });
3536  // If we've implicitly added *all* of the overloadable attrs to this
3537  // chain, emitting a "previous redecl" note is pointless.
3538  DiagOld = OldIter == Old->redecls_end() ? nullptr : *OldIter;
3539  }
3540 
3541  if (DiagOld)
3542  Diag(DiagOld->getLocation(),
3543  diag::note_attribute_overloadable_prev_overload)
3544  << OldOvl;
3545 
3546  if (OldOvl)
3547  New->addAttr(OverloadableAttr::CreateImplicit(Context));
3548  else
3549  New->dropAttr<OverloadableAttr>();
3550  }
3551  }
3552 
3553  // If a function is first declared with a calling convention, but is later
3554  // declared or defined without one, all following decls assume the calling
3555  // convention of the first.
3556  //
3557  // It's OK if a function is first declared without a calling convention,
3558  // but is later declared or defined with the default calling convention.
3559  //
3560  // To test if either decl has an explicit calling convention, we look for
3561  // AttributedType sugar nodes on the type as written. If they are missing or
3562  // were canonicalized away, we assume the calling convention was implicit.
3563  //
3564  // Note also that we DO NOT return at this point, because we still have
3565  // other tests to run.
3566  QualType OldQType = Context.getCanonicalType(Old->getType());
3567  QualType NewQType = Context.getCanonicalType(New->getType());
3568  const FunctionType *OldType = cast<FunctionType>(OldQType);
3569  const FunctionType *NewType = cast<FunctionType>(NewQType);
3570  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
3571  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
3572  bool RequiresAdjustment = false;
3573 
3574  if (OldTypeInfo.getCC() != NewTypeInfo.getCC()) {
3575  FunctionDecl *First = Old->getFirstDecl();
3576  const FunctionType *FT =
3577  First->getType().getCanonicalType()->castAs<FunctionType>();
3578  FunctionType::ExtInfo FI = FT->getExtInfo();
3579  bool NewCCExplicit = getCallingConvAttributedType(New->getType());
3580  if (!NewCCExplicit) {
3581  // Inherit the CC from the previous declaration if it was specified
3582  // there but not here.
3583  NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3584  RequiresAdjustment = true;
3585  } else if (Old->getBuiltinID()) {
3586  // Builtin attribute isn't propagated to the new one yet at this point,
3587  // so we check if the old one is a builtin.
3588 
3589  // Calling Conventions on a Builtin aren't really useful and setting a
3590  // default calling convention and cdecl'ing some builtin redeclarations is
3591  // common, so warn and ignore the calling convention on the redeclaration.
3592  Diag(New->getLocation(), diag::warn_cconv_unsupported)
3593  << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3594  << (int)CallingConventionIgnoredReason::BuiltinFunction;
3595  NewTypeInfo = NewTypeInfo.withCallingConv(OldTypeInfo.getCC());
3596  RequiresAdjustment = true;
3597  } else {
3598  // Calling conventions aren't compatible, so complain.
3599  bool FirstCCExplicit = getCallingConvAttributedType(First->getType());
3600  Diag(New->getLocation(), diag::err_cconv_change)
3601  << FunctionType::getNameForCallConv(NewTypeInfo.getCC())
3602  << !FirstCCExplicit
3603  << (!FirstCCExplicit ? "" :
3604  FunctionType::getNameForCallConv(FI.getCC()));
3605 
3606  // Put the note on the first decl, since it is the one that matters.
3607  Diag(First->getLocation(), diag::note_previous_declaration);
3608  return true;
3609  }
3610  }
3611 
3612  // FIXME: diagnose the other way around?
3613  if (OldTypeInfo.getNoReturn() && !NewTypeInfo.getNoReturn()) {
3614  NewTypeInfo = NewTypeInfo.withNoReturn(true);
3615  RequiresAdjustment = true;
3616  }
3617 
3618  // Merge regparm attribute.
3619  if (OldTypeInfo.getHasRegParm() != NewTypeInfo.getHasRegParm() ||
3620  OldTypeInfo.getRegParm() != NewTypeInfo.getRegParm()) {
3621  if (NewTypeInfo.getHasRegParm()) {
3622  Diag(New->getLocation(), diag::err_regparm_mismatch)
3623  << NewType->getRegParmType()
3624  << OldType->getRegParmType();
3625  Diag(OldLocation, diag::note_previous_declaration);
3626  return true;
3627  }
3628 
3629  NewTypeInfo = NewTypeInfo.withRegParm(OldTypeInfo.getRegParm());
3630  RequiresAdjustment = true;
3631  }
3632 
3633  // Merge ns_returns_retained attribute.
3634  if (OldTypeInfo.getProducesResult() != NewTypeInfo.getProducesResult()) {
3635  if (NewTypeInfo.getProducesResult()) {
3636  Diag(New->getLocation(), diag::err_function_attribute_mismatch)
3637  << "'ns_returns_retained'";
3638  Diag(OldLocation, diag::note_previous_declaration);
3639  return true;
3640  }
3641 
3642  NewTypeInfo = NewTypeInfo.withProducesResult(true);
3643  RequiresAdjustment = true;
3644  }
3645 
3646  if (OldTypeInfo.getNoCallerSavedRegs() !=
3647  NewTypeInfo.getNoCallerSavedRegs()) {
3648  if (NewTypeInfo.getNoCallerSavedRegs()) {
3649  AnyX86NoCallerSavedRegistersAttr *Attr =
3650  New->getAttr<AnyX86NoCallerSavedRegistersAttr>();
3651  Diag(New->getLocation(), diag::err_function_attribute_mismatch) << Attr;
3652  Diag(OldLocation, diag::note_previous_declaration);
3653  return true;
3654  }
3655 
3656  NewTypeInfo = NewTypeInfo.withNoCallerSavedRegs(true);
3657  RequiresAdjustment = true;
3658  }
3659 
3660  if (RequiresAdjustment) {
3661  const FunctionType *AdjustedType = New->getType()->getAs<FunctionType>();
3662  AdjustedType = Context.adjustFunctionType(AdjustedType, NewTypeInfo);
3663  New->setType(QualType(AdjustedType, 0));
3664  NewQType = Context.getCanonicalType(New->getType());
3665  }
3666 
3667  // If this redeclaration makes the function inline, we may need to add it to
3668  // UndefinedButUsed.
3669  if (!Old->isInlined() && New->isInlined() &&
3670  !New->hasAttr<GNUInlineAttr>() &&
3671  !getLangOpts().GNUInline &&
3672  Old->isUsed(false) &&
3673  !Old->isDefined() && !New->isThisDeclarationADefinition())
3674  UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
3675  SourceLocation()));
3676 
3677  // If this redeclaration makes it newly gnu_inline, we don't want to warn
3678  // about it.
3679  if (New->hasAttr<GNUInlineAttr>() &&
3680  Old->isInlined() && !Old->hasAttr<GNUInlineAttr>()) {
3681  UndefinedButUsed.erase(Old->getCanonicalDecl());
3682  }
3683 
3684  // If pass_object_size params don't match up perfectly, this isn't a valid
3685  // redeclaration.
3686  if (Old->getNumParams() > 0 && Old->getNumParams() == New->getNumParams() &&
3687  !hasIdenticalPassObjectSizeAttrs(Old, New)) {
3688  Diag(New->getLocation(), diag::err_different_pass_object_size_params)
3689  << New->getDeclName();
3690  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3691  return true;
3692  }
3693 
3694  if (getLangOpts().CPlusPlus) {
3695  // C++1z [over.load]p2
3696  // Certain function declarations cannot be overloaded:
3697  // -- Function declarations that differ only in the return type,
3698  // the exception specification, or both cannot be overloaded.
3699 
3700  // Check the exception specifications match. This may recompute the type of
3701  // both Old and New if it resolved exception specifications, so grab the
3702  // types again after this. Because this updates the type, we do this before
3703  // any of the other checks below, which may update the "de facto" NewQType
3704  // but do not necessarily update the type of New.
3705  if (CheckEquivalentExceptionSpec(Old, New))
3706  return true;
3707  OldQType = Context.getCanonicalType(Old->getType());
3708  NewQType = Context.getCanonicalType(New->getType());
3709 
3710  // Go back to the type source info to compare the declared return types,
3711  // per C++1y [dcl.type.auto]p13:
3712  // Redeclarations or specializations of a function or function template
3713  // with a declared return type that uses a placeholder type shall also
3714  // use that placeholder, not a deduced type.
3715  QualType OldDeclaredReturnType = Old->getDeclaredReturnType();
3716  QualType NewDeclaredReturnType = New->getDeclaredReturnType();
3717  if (!Context.hasSameType(OldDeclaredReturnType, NewDeclaredReturnType) &&
3718  canFullyTypeCheckRedeclaration(New, Old, NewDeclaredReturnType,
3719  OldDeclaredReturnType)) {
3720  QualType ResQT;
3721  if (NewDeclaredReturnType->isObjCObjectPointerType() &&
3722  OldDeclaredReturnType->isObjCObjectPointerType())
3723  // FIXME: This does the wrong thing for a deduced return type.
3724  ResQT = Context.mergeObjCGCQualifiers(NewQType, OldQType);
3725  if (ResQT.isNull()) {
3726  if (New->isCXXClassMember() && New->isOutOfLine())
3727  Diag(New->getLocation(), diag::err_member_def_does_not_match_ret_type)
3728  << New << New->getReturnTypeSourceRange();
3729  else
3730  Diag(New->getLocation(), diag::err_ovl_diff_return_type)
3731  << New->getReturnTypeSourceRange();
3732  Diag(OldLocation, PrevDiag) << Old << Old->getType()
3733  << Old->getReturnTypeSourceRange();
3734  return true;
3735  }
3736  else
3737  NewQType = ResQT;
3738  }
3739 
3740  QualType OldReturnType = OldType->getReturnType();
3741  QualType NewReturnType = cast<FunctionType>(NewQType)->getReturnType();
3742  if (OldReturnType != NewReturnType) {
3743  // If this function has a deduced return type and has already been
3744  // defined, copy the deduced value from the old declaration.
3745  AutoType *OldAT = Old->getReturnType()->getContainedAutoType();
3746  if (OldAT && OldAT->isDeduced()) {
3747  QualType DT = OldAT->getDeducedType();
3748  if (DT.isNull()) {
3749  New->setType(SubstAutoTypeDependent(New->getType()));
3750  NewQType = Context.getCanonicalType(SubstAutoTypeDependent(NewQType));
3751  } else {
3752  New->setType(SubstAutoType(New->getType(), DT));
3753  NewQType = Context.getCanonicalType(SubstAutoType(NewQType, DT));
3754  }
3755  }
3756  }
3757 
3758  const CXXMethodDecl *OldMethod = dyn_cast<CXXMethodDecl>(Old);
3759  CXXMethodDecl *NewMethod = dyn_cast<CXXMethodDecl>(New);
3760  if (OldMethod && NewMethod) {
3761  // Preserve triviality.
3762  NewMethod->setTrivial(OldMethod->isTrivial());
3763 
3764  // MSVC allows explicit template specialization at class scope:
3765  // 2 CXXMethodDecls referring to the same function will be injected.
3766  // We don't want a redeclaration error.
3767  bool IsClassScopeExplicitSpecialization =
3768  OldMethod->isFunctionTemplateSpecialization() &&
3769  NewMethod->isFunctionTemplateSpecialization();
3770  bool isFriend = NewMethod->getFriendObjectKind();
3771 
3772  if (!isFriend && NewMethod->getLexicalDeclContext()->isRecord() &&
3773  !IsClassScopeExplicitSpecialization) {
3774  // -- Member function declarations with the same name and the
3775  // same parameter types cannot be overloaded if any of them
3776  // is a static member function declaration.
3777  if (OldMethod->isStatic() != NewMethod->isStatic()) {
3778  Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
3779  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3780  return true;
3781  }
3782 
3783  // C++ [class.mem]p1:
3784  // [...] A member shall not be declared twice in the
3785  // member-specification, except that a nested class or member
3786  // class template can be declared and then later defined.
3787  if (!inTemplateInstantiation()) {
3788  unsigned NewDiag;
3789  if (isa<CXXConstructorDecl>(OldMethod))
3790  NewDiag = diag::err_constructor_redeclared;
3791  else if (isa<CXXDestructorDecl>(NewMethod))
3792  NewDiag = diag::err_destructor_redeclared;
3793  else if (isa<CXXConversionDecl>(NewMethod))
3794  NewDiag = diag::err_conv_function_redeclared;
3795  else
3796  NewDiag = diag::err_member_redeclared;
3797 
3798  Diag(New->getLocation(), NewDiag);
3799  } else {
3800  Diag(New->getLocation(), diag::err_member_redeclared_in_instantiation)
3801  << New << New->getType();
3802  }
3803  Diag(OldLocation, PrevDiag) << Old << Old->getType();
3804  return true;
3805 
3806  // Complain if this is an explicit declaration of a special
3807  // member that was initially declared implicitly.
3808  //
3809  // As an exception, it's okay to befriend such methods in order
3810  // to permit the implicit constructor/destructor/operator calls.
3811  } else if (OldMethod->isImplicit()) {
3812  if (isFriend) {
3813  NewMethod->setImplicit();
3814  } else {
3815  Diag(NewMethod->getLocation(),
3816  diag::err_definition_of_implicitly_declared_member)
3817  << New << getSpecialMember(OldMethod);
3818  return true;
3819  }
3820  } else if (OldMethod->getFirstDecl()->isExplicitlyDefaulted() && !isFriend) {
3821  Diag(NewMethod->getLocation(),
3822  diag::err_definition_of_explicitly_defaulted_member)
3823  << getSpecialMember(OldMethod);
3824  return true;
3825  }
3826  }
3827 
3828  // C++11 [dcl.attr.noreturn]p1:
3829  // The first declaration of a function shall specify the noreturn
3830  // attribute if any declaration of that function specifies the noreturn
3831  // attribute.
3832  if (const auto *NRA = New->getAttr<CXX11NoReturnAttr>())
3833  if (!Old->hasAttr<CXX11NoReturnAttr>()) {
3834  Diag(NRA->getLocation(), diag::err_attribute_missing_on_first_decl)
3835  << NRA;
3836  Diag(Old->getLocation(), diag::note_previous_declaration);
3837  }
3838 
3839  // C++11 [dcl.attr.depend]p2:
3840  // The first declaration of a function shall specify the
3841  // carries_dependency attribute for its declarator-id if any declaration
3842  // of the function specifies the carries_dependency attribute.
3843  const CarriesDependencyAttr *CDA = New->getAttr<CarriesDependencyAttr>();
3844  if (CDA && !Old->hasAttr<CarriesDependencyAttr>()) {
3845  Diag(CDA->getLocation(),
3846  diag::err_carries_dependency_missing_on_first_decl) << 0/*Function*/;
3847  Diag(Old->getFirstDecl()->getLocation(),
3848  diag::note_carries_dependency_missing_first_decl) << 0/*Function*/;
3849  }
3850 
3851  // (C++98 8.3.5p3):
3852  // All declarations for a function shall agree exactly in both the
3853  // return type and the parameter-type-list.
3854  // We also want to respect all the extended bits except noreturn.
3855 
3856  // noreturn should now match unless the old type info didn't have it.
3857  QualType OldQTypeForComparison = OldQType;
3858  if (!OldTypeInfo.getNoReturn() && NewTypeInfo.getNoReturn()) {
3859  auto *OldType = OldQType->castAs<FunctionProtoType>();
3860  const FunctionType *OldTypeForComparison
3861  = Context.adjustFunctionType(OldType, OldTypeInfo.withNoReturn(true));
3862  OldQTypeForComparison = QualType(OldTypeForComparison, 0);
3863  assert(OldQTypeForComparison.isCanonical());
3864  }
3865 
3866  if (haveIncompatibleLanguageLinkages(Old, New)) {
3867  // As a special case, retain the language linkage from previous
3868  // declarations of a friend function as an extension.
3869  //
3870  // This liberal interpretation of C++ [class.friend]p3 matches GCC/MSVC
3871  // and is useful because there's otherwise no way to specify language
3872  // linkage within class scope.
3873  //
3874  // Check cautiously as the friend object kind isn't yet complete.
3875  if (New->getFriendObjectKind() != Decl::FOK_None) {
3876  Diag(New->getLocation(), diag::ext_retained_language_linkage) << New;
3877  Diag(OldLocation, PrevDiag);
3878  } else {
3879  Diag(New->getLocation(), diag::err_different_language_linkage) << New;
3880  Diag(OldLocation, PrevDiag);
3881  return true;
3882  }
3883  }
3884 
3885  // If the function types are compatible, merge the declarations. Ignore the
3886  // exception specifier because it was already checked above in
3887  // CheckEquivalentExceptionSpec, and we don't want follow-on diagnostics
3888  // about incompatible types under -fms-compatibility.
3889  if (Context.hasSameFunctionTypeIgnoringExceptionSpec(OldQTypeForComparison,
3890  NewQType))
3891  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3892 
3893  // If the types are imprecise (due to dependent constructs in friends or
3894  // local extern declarations), it's OK if they differ. We'll check again
3895  // during instantiation.
3896  if (!canFullyTypeCheckRedeclaration(New, Old, NewQType, OldQType))
3897  return false;
3898 
3899  // Fall through for conflicting redeclarations and redefinitions.
3900  }
3901 
3902  // C: Function types need to be compatible, not identical. This handles
3903  // duplicate function decls like "void f(int); void f(enum X);" properly.
3904  if (!getLangOpts().CPlusPlus &&
3905  Context.typesAreCompatible(OldQType, NewQType)) {
3906  const FunctionType *OldFuncType = OldQType->getAs<FunctionType>();
3907  const FunctionType *NewFuncType = NewQType->getAs<FunctionType>();
3908  const FunctionProtoType *OldProto = nullptr;
3909  if (MergeTypeWithOld && isa<FunctionNoProtoType>(NewFuncType) &&
3910  (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
3911  // The old declaration provided a function prototype, but the
3912  // new declaration does not. Merge in the prototype.
3913  assert(!OldProto->hasExceptionSpec() && "Exception spec in C");
3914  SmallVector<QualType, 16> ParamTypes(OldProto->param_types());
3915  NewQType =
3916  Context.getFunctionType(NewFuncType->getReturnType(), ParamTypes,
3917  OldProto->getExtProtoInfo());
3918  New->setType(NewQType);
3919  New->setHasInheritedPrototype();
3920 
3921  // Synthesize parameters with the same types.
3923  for (const auto &ParamType : OldProto->param_types()) {
3924  ParmVarDecl *Param = ParmVarDecl::Create(Context, New, SourceLocation(),
3925  SourceLocation(), nullptr,
3926  ParamType, /*TInfo=*/nullptr,
3927  SC_None, nullptr);
3928  Param->setScopeInfo(0, Params.size());
3929  Param->setImplicit();
3930  Params.push_back(Param);
3931  }
3932 
3933  New->setParams(Params);
3934  }
3935 
3936  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
3937  }
3938 
3939  // Check if the function types are compatible when pointer size address
3940  // spaces are ignored.
3941  if (Context.hasSameFunctionTypeIgnoringPtrSizes(OldQType, NewQType))
3942  return false;
3943 
3944  // GNU C permits a K&R definition to follow a prototype declaration
3945  // if the declared types of the parameters in the K&R definition
3946  // match the types in the prototype declaration, even when the
3947  // promoted types of the parameters from the K&R definition differ
3948  // from the types in the prototype. GCC then keeps the types from
3949  // the prototype.
3950  //
3951  // If a variadic prototype is followed by a non-variadic K&R definition,
3952  // the K&R definition becomes variadic. This is sort of an edge case, but
3953  // it's legal per the standard depending on how you read C99 6.7.5.3p15 and
3954  // C99 6.9.1p8.
3955  if (!getLangOpts().CPlusPlus &&
3956  Old->hasPrototype() && !New->hasPrototype() &&
3957  New->getType()->getAs<FunctionProtoType>() &&
3958  Old->getNumParams() == New->getNumParams()) {
3959  SmallVector<QualType, 16> ArgTypes;
3961  const FunctionProtoType *OldProto
3962  = Old->getType()->getAs<FunctionProtoType>();
3963  const FunctionProtoType *NewProto
3964  = New->getType()->getAs<FunctionProtoType>();
3965 
3966  // Determine whether this is the GNU C extension.
3967  QualType MergedReturn = Context.mergeTypes(OldProto->getReturnType(),
3968  NewProto->getReturnType());
3969  bool LooseCompatible = !MergedReturn.isNull();
3970  for (unsigned Idx = 0, End = Old->getNumParams();
3971  LooseCompatible && Idx != End; ++Idx) {
3972  ParmVarDecl *OldParm = Old->getParamDecl(Idx);
3973  ParmVarDecl *NewParm = New->getParamDecl(Idx);
3974  if (Context.typesAreCompatible(OldParm->getType(),
3975  NewProto->getParamType(Idx))) {
3976  ArgTypes.push_back(NewParm->getType());
3977  } else if (Context.typesAreCompatible(OldParm->getType(),
3978  NewParm->getType(),
3979  /*CompareUnqualified=*/true)) {
3980  GNUCompatibleParamWarning Warn = { OldParm, NewParm,
3981  NewProto->getParamType(Idx) };
3982  Warnings.push_back(Warn);
3983  ArgTypes.push_back(NewParm->getType());
3984  } else
3985  LooseCompatible = false;
3986  }
3987 
3988  if (LooseCompatible) {
3989  for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
3990  Diag(Warnings[Warn].NewParm->getLocation(),
3991  diag::ext_param_promoted_not_compatible_with_prototype)
3992  << Warnings[Warn].PromotedType
3993  << Warnings[Warn].OldParm->getType();
3994  if (Warnings[Warn].OldParm->getLocation().isValid())
3995  Diag(Warnings[Warn].OldParm->getLocation(),
3996  diag::note_previous_declaration);
3997  }
3998 
3999  if (MergeTypeWithOld)
4000  New->setType(Context.getFunctionType(MergedReturn, ArgTypes,
4001  OldProto->getExtProtoInfo()));
4002  return MergeCompatibleFunctionDecls(New, Old, S, MergeTypeWithOld);
4003  }
4004 
4005  // Fall through to diagnose conflicting types.
4006  }
4007 
4008  // A function that has already been declared has been redeclared or
4009  // defined with a different type; show an appropriate diagnostic.
4010 
4011  // If the previous declaration was an implicitly-generated builtin
4012  // declaration, then at the very least we should use a specialized note.
4013  unsigned BuiltinID;
4014  if (Old->isImplicit() && (BuiltinID = Old->getBuiltinID())) {
4015  // If it's actually a library-defined builtin function like 'malloc'
4016  // or 'printf', just warn about the incompatible redeclaration.
4017  if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
4018  Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
4019  Diag(OldLocation, diag::note_previous_builtin_declaration)
4020  << Old << Old->getType();
4021  return false;
4022  }
4023 
4024  PrevDiag = diag::note_previous_builtin_declaration;
4025  }
4026 
4027  Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
4028  Diag(OldLocation, PrevDiag) << Old << Old->getType();
4029  return true;
4030 }
4031 
4032 /// Completes the merge of two function declarations that are
4033 /// known to be compatible.
4034 ///
4035 /// This routine handles the merging of attributes and other
4036 /// properties of function declarations from the old declaration to
4037 /// the new declaration, once we know that New is in fact a
4038 /// redeclaration of Old.
4039 ///
4040 /// \returns false
4042  Scope *S, bool MergeTypeWithOld) {
4043  // Merge the attributes
4044  mergeDeclAttributes(New, Old);
4045 
4046  // Merge "pure" flag.
4047  if (Old->isPure())
4048  New->setPure();
4049 
4050  // Merge "used" flag.
4051  if (Old->getMostRecentDecl()->isUsed(false))
4052  New->setIsUsed();
4053 
4054  // Merge attributes from the parameters. These can mismatch with K&R
4055  // declarations.
4056  if (New->getNumParams() == Old->getNumParams())
4057  for (unsigned i = 0, e = New->getNumParams(); i != e; ++i) {
4058  ParmVarDecl *NewParam = New->getParamDecl(i);
4059  ParmVarDecl *OldParam = Old->getParamDecl(i);
4060  mergeParamDeclAttributes(NewParam, OldParam, *this);
4061  mergeParamDeclTypes(NewParam, OldParam, *this);
4062  }
4063 
4064  if (getLangOpts().CPlusPlus)
4065  return MergeCXXFunctionDecl(New, Old, S);
4066 
4067  // Merge the function types so the we get the composite types for the return
4068  // and argument types. Per C11 6.2.7/4, only update the type if the old decl
4069  // was visible.
4070  QualType Merged = Context.mergeTypes(Old->getType(), New->getType());
4071  if (!Merged.isNull() && MergeTypeWithOld)
4072  New->setType(Merged);
4073 
4074  return false;
4075 }
4076 
4078  ObjCMethodDecl *oldMethod) {
4079  // Merge the attributes, including deprecated/unavailable
4080  AvailabilityMergeKind MergeKind =
4081  isa<ObjCProtocolDecl>(oldMethod->getDeclContext())
4082  ? (oldMethod->isOptional() ? AMK_OptionalProtocolImplementation
4083  : AMK_ProtocolImplementation)
4084  : isa<ObjCImplDecl>(newMethod->getDeclContext()) ? AMK_Redeclaration
4085  : AMK_Override;
4086 
4087  mergeDeclAttributes(newMethod, oldMethod, MergeKind);
4088 
4089  // Merge attributes from the parameters.
4091  oe = oldMethod->param_end();
4093  ni = newMethod->param_begin(), ne = newMethod->param_end();
4094  ni != ne && oi != oe; ++ni, ++oi)
4095  mergeParamDeclAttributes(*ni, *oi, *this);
4096 
4097  CheckObjCMethodOverride(newMethod, oldMethod);
4098 }
4099 
4100 static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl* Old) {
4101  assert(!S.Context.hasSameType(New->getType(), Old->getType()));
4102 
4104  ? diag::err_redefinition_different_type
4105  : diag::err_redeclaration_different_type)
4106  << New->getDeclName() << New->getType() << Old->getType();
4107 
4108  diag::kind PrevDiag;
4109  SourceLocation OldLocation;
4110  std::tie(PrevDiag, OldLocation)
4112  S.Diag(OldLocation, PrevDiag);
4113  New->setInvalidDecl();
4114 }
4115 
4116 /// MergeVarDeclTypes - We parsed a variable 'New' which has the same name and
4117 /// scope as a previous declaration 'Old'. Figure out how to merge their types,
4118 /// emitting diagnostics as appropriate.
4119 ///
4120 /// Declarations using the auto type specifier (C++ [decl.spec.auto]) call back
4121 /// to here in AddInitializerToDecl. We can't check them before the initializer
4122 /// is attached.
4124  bool MergeTypeWithOld) {
4125  if (New->isInvalidDecl() || Old->isInvalidDecl())
4126  return;
4127 
4128  QualType MergedT;
4129  if (getLangOpts().CPlusPlus) {
4130  if (New->getType()->isUndeducedType()) {
4131  // We don't know what the new type is until the initializer is attached.
4132  return;
4133  } else if (Context.hasSameType(New->getType(), Old->getType())) {
4134  // These could still be something that needs exception specs checked.
4135  return MergeVarDeclExceptionSpecs(New, Old);
4136  }
4137  // C++ [basic.link]p10:
4138  // [...] the types specified by all declarations referring to a given
4139  // object or function shall be identical, except that declarations for an
4140  // array object can specify array types that differ by the presence or
4141  // absence of a major array bound (8.3.4).
4142  else if (Old->getType()->isArrayType() && New->getType()->isArrayType()) {
4143  const ArrayType *OldArray = Context.getAsArrayType(Old->getType());
4144  const ArrayType *NewArray = Context.getAsArrayType(New->getType());
4145 
4146  // We are merging a variable declaration New into Old. If it has an array
4147  // bound, and that bound differs from Old's bound, we should diagnose the
4148  // mismatch.
4149  if (!NewArray->isIncompleteArrayType() && !NewArray->isDependentType()) {
4150  for (VarDecl *PrevVD = Old->getMostRecentDecl(); PrevVD;
4151  PrevVD = PrevVD->getPreviousDecl()) {
4152  QualType PrevVDTy = PrevVD->getType();
4153  if (PrevVDTy->isIncompleteArrayType() || PrevVDTy->isDependentType())
4154  continue;
4155 
4156  if (!Context.hasSameType(New->getType(), PrevVDTy))
4157  return diagnoseVarDeclTypeMismatch(*this, New, PrevVD);
4158  }
4159  }
4160 
4161  if (OldArray->isIncompleteArrayType() && NewArray->isArrayType()) {
4162  if (Context.hasSameType(OldArray->getElementType(),
4163  NewArray->getElementType()))
4164  MergedT = New->getType();
4165  }
4166  // FIXME: Check visibility. New is hidden but has a complete type. If New
4167  // has no array bound, it should not inherit one from Old, if Old is not
4168  // visible.
4169  else if (OldArray->isArrayType() && NewArray->isIncompleteArrayType()) {
4170  if (Context.hasSameType(OldArray->getElementType(),
4171  NewArray->getElementType()))
4172  MergedT = Old->getType();
4173  }
4174  }
4175  else if (New->getType()->isObjCObjectPointerType() &&
4176  Old->getType()->isObjCObjectPointerType()) {
4177  MergedT = Context.mergeObjCGCQualifiers(New->getType(),
4178  Old->getType());
4179  }
4180  } else {
4181  // C 6.2.7p2:
4182  // All declarations that refer to the same object or function shall have
4183  // compatible type.
4184  MergedT = Context.mergeTypes(New->getType(), Old->getType());
4185  }
4186  if (MergedT.isNull()) {
4187  // It's OK if we couldn't merge types if either type is dependent, for a
4188  // block-scope variable. In other cases (static data members of class
4189  // templates, variable templates, ...), we require the types to be
4190  // equivalent.
4191  // FIXME: The C++ standard doesn't say anything about this.
4192  if ((New->getType()->isDependentType() ||
4193  Old->getType()->isDependentType()) && New->isLocalVarDecl()) {
4194  // If the old type was dependent, we can't merge with it, so the new type
4195  // becomes dependent for now. We'll reproduce the original type when we
4196  // instantiate the TypeSourceInfo for the variable.
4197  if (!New->getType()->isDependentType() && MergeTypeWithOld)
4198  New->setType(Context.DependentTy);
4199  return;
4200  }
4201  return diagnoseVarDeclTypeMismatch(*this, New, Old);
4202  }
4203 
4204  // Don't actually update the type on the new declaration if the old
4205  // declaration was an extern declaration in a different scope.
4206  if (MergeTypeWithOld)
4207  New->setType(MergedT);
4208 }
4209 
4210 static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD,
4212  // C11 6.2.7p4:
4213  // For an identifier with internal or external linkage declared
4214  // in a scope in which a prior declaration of that identifier is
4215  // visible, if the prior declaration specifies internal or
4216  // external linkage, the type of the identifier at the later
4217  // declaration becomes the composite type.
4218  //
4219  // If the variable isn't visible, we do not merge with its type.
4220  if (Previous.isShadowed())
4221  return false;
4222 
4223  if (S.getLangOpts().CPlusPlus) {
4224  // C++11 [dcl.array]p3:
4225  // If there is a preceding declaration of the entity in the same
4226  // scope in which the bound was specified, an omitted array bound
4227  // is taken to be the same as in that earlier declaration.
4228  return NewVD->isPreviousDeclInSameBlockScope() ||
4229  (!OldVD->getLexicalDeclContext()->isFunctionOrMethod() &&
4231  } else {
4232  // If the old declaration was function-local, don't merge with its
4233  // type unless we're in the same function.
4234  return !OldVD->getLexicalDeclContext()->isFunctionOrMethod() ||
4235  OldVD->getLexicalDeclContext() == NewVD->getLexicalDeclContext();
4236  }
4237 }
4238 
4239 /// MergeVarDecl - We just parsed a variable 'New' which has the same name
4240 /// and scope as a previous declaration 'Old'. Figure out how to resolve this
4241 /// situation, merging decls or emitting diagnostics as appropriate.
4242 ///
4243 /// Tentative definition rules (C99 6.9.2p2) are checked by
4244 /// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
4245 /// definitions here, since the initializer hasn't been attached.
4246 ///
4248  // If the new decl is already invalid, don't do any other checking.
4249  if (New->isInvalidDecl())
4250  return;
4251 
4252  if (!shouldLinkPossiblyHiddenDecl(Previous, New))
4253  return;
4254 
4255  VarTemplateDecl *NewTemplate = New->getDescribedVarTemplate();
4256 
4257  // Verify the old decl was also a variable or variable template.
4258  VarDecl *Old = nullptr;
4259  VarTemplateDecl *OldTemplate = nullptr;
4260  if (Previous.isSingleResult()) {
4261  if (NewTemplate) {
4262  OldTemplate = dyn_cast<VarTemplateDecl>(Previous.getFoundDecl());
4263  Old = OldTemplate ? OldTemplate->getTemplatedDecl() : nullptr;
4264 
4265  if (auto *Shadow =
4266  dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4267  if (checkUsingShadowRedecl<VarTemplateDecl>(*this, Shadow, NewTemplate))
4268  return New->setInvalidDecl();
4269  } else {
4270  Old = dyn_cast<VarDecl>(Previous.getFoundDecl());
4271 
4272  if (auto *Shadow =
4273  dyn_cast<UsingShadowDecl>(Previous.getRepresentativeDecl()))
4274  if (checkUsingShadowRedecl<VarDecl>(*this, Shadow, New))
4275  return New->setInvalidDecl();
4276  }
4277  }
4278  if (!Old) {
4279  Diag(New->getLocation(), diag::err_redefinition_different_kind)
4280  << New->getDeclName();
4281  notePreviousDefinition(Previous.getRepresentativeDecl(),
4282  New->getLocation());
4283  return New->setInvalidDecl();
4284  }
4285 
4286  // If the old declaration was found in an inline namespace and the new
4287  // declaration was qualified, update the DeclContext to match.
4289 
4290  // Ensure the template parameters are compatible.
4291  if (NewTemplate &&
4292  !TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
4293  OldTemplate->getTemplateParameters(),
4294  /*Complain=*/true, TPL_TemplateMatch))
4295  return New->setInvalidDecl();
4296 
4297  // C++ [class.mem]p1:
4298  // A member shall not be declared twice in the member-specification [...]
4299  //
4300  // Here, we need only consider static data members.
4301  if (Old->isStaticDataMember() && !New->isOutOfLine()) {
4302  Diag(New->getLocation(), diag::err_duplicate_member)
4303  << New->getIdentifier();
4304  Diag(Old->getLocation(), diag::note_previous_declaration);
4305  New->setInvalidDecl();
4306  }
4307 
4308  mergeDeclAttributes(New, Old);
4309  // Warn if an already-declared variable is made a weak_import in a subsequent
4310  // declaration
4311  if (New->hasAttr<WeakImportAttr>() &&
4312  Old->getStorageClass() == SC_None &&
4313  !Old->hasAttr<WeakImportAttr>()) {
4314  Diag(New->getLocation(), diag::warn_weak_import) << New->getDeclName();
4315  Diag(Old->getLocation(), diag::note_previous_declaration);
4316  // Remove weak_import attribute on new declaration.
4317  New->dropAttr<WeakImportAttr>();
4318  }
4319 
4320  if (const auto *ILA = New->getAttr<InternalLinkageAttr>())
4321  if (!Old->hasAttr<InternalLinkageAttr>()) {
4322  Diag(New->getLocation(), diag::err_attribute_missing_on_first_decl)
4323  << ILA;
4324  Diag(Old->getLocation(), diag::note_previous_declaration);
4325  New->dropAttr<InternalLinkageAttr>();
4326  }
4327 
4328  // Merge the types.
4329  VarDecl *MostRecent = Old->getMostRecentDecl();
4330  if (MostRecent != Old) {
4331  MergeVarDeclTypes(New, MostRecent,
4332  mergeTypeWithPrevious(*this, New, MostRecent, Previous));
4333  if (New->isInvalidDecl())
4334  return;
4335  }
4336 
4337  MergeVarDeclTypes(New, Old, mergeTypeWithPrevious(*this, New, Old, Previous));
4338  if (New->isInvalidDecl())
4339  return;
4340 
4341  diag::kind PrevDiag;
4342  SourceLocation OldLocation;
4343  std::tie(PrevDiag, OldLocation) =
4345 
4346  // [dcl.stc]p8: Check if we have a non-static decl followed by a static.
4347  if (New->getStorageClass() == SC_Static &&
4348  !New->isStaticDataMember() &&
4349  Old->hasExternalFormalLinkage()) {
4350  if (getLangOpts().MicrosoftExt) {
4351  Diag(New->getLocation(), diag::ext_static_non_static)
4352  << New->getDeclName();
4353  Diag(OldLocation, PrevDiag);
4354  } else {
4355  Diag(New->getLocation(), diag::err_static_non_static)
4356  << New->getDeclName();
4357  Diag(OldLocation, PrevDiag);
4358  return New->setInvalidDecl();
4359  }
4360  }
4361  // C99 6.2.2p4:
4362  // For an identifier declared with the storage-class specifier
4363  // extern in a scope in which a prior declaration of that
4364  // identifier is visible,23) if the prior declaration specifies
4365  // internal or external linkage, the linkage of the identifier at
4366  // the later declaration is the same as the linkage specified at
4367  // the prior declaration. If no prior declaration is visible, or
4368  // if the prior declaration specifies no linkage, then the
4369  // identifier has external linkage.
4370  if (New->hasExternalStorage() && Old->hasLinkage())
4371  /* Okay */;
4372  else if (New->getCanonicalDecl()->getStorageClass() != SC_Static &&
4373  !New->isStaticDataMember() &&
4375  Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
4376  Diag(OldLocation, PrevDiag);
4377  return New->setInvalidDecl();
4378  }
4379 
4380  // Check if extern is followed by non-extern and vice-versa.
4381  if (New->hasExternalStorage() &&
4382  !Old->hasLinkage() && Old->isLocalVarDeclOrParm()) {
4383  Diag(New->getLocation(), diag::err_extern_non_extern) << New->getDeclName();
4384  Diag(OldLocation, PrevDiag);
4385  return New->setInvalidDecl();
4386  }
4387  if (Old->hasLinkage() && New->isLocalVarDeclOrParm() &&
4388  !New->hasExternalStorage()) {
4389  Diag(New->getLocation(), diag::err_non_extern_extern) << New->getDeclName();
4390  Diag(OldLocation, PrevDiag);
4391  return New->setInvalidDecl();
4392  }
4393 
4394  if (CheckRedeclarationInModule(New, Old))
4395  return;
4396 
4397  // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
4398 
4399  // FIXME: The test for external storage here seems wrong? We still
4400  // need to check for mismatches.
4401  if (!New->hasExternalStorage() && !New->isFileVarDecl() &&
4402  // Don't complain about out-of-line definitions of static members.
4403  !(Old->getLexicalDeclContext()->isRecord() &&
4404  !New->getLexicalDeclContext()->isRecord())) {
4405  Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
4406  Diag(OldLocation, PrevDiag);
4407  return New->setInvalidDecl();
4408  }
4409 
4410  if (New->isInline() && !Old->getMostRecentDecl()->isInline()) {
4411  if (VarDecl *Def = Old->getDefinition()) {
4412  // C++1z [dcl.fcn.spec]p4:
4413  // If the definition of a variable appears in a translation unit before
4414  // its first declaration as inline, the program is ill-formed.
4415  Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
4416  Diag(Def->getLocation(), diag::note_previous_definition);
4417  }
4418  }
4419 
4420  // If this redeclaration makes the variable inline, we may need to add it to
4421  // UndefinedButUsed.
4422  if (!Old->isInline() && New->isInline() && Old->isUsed(false) &&
4423  !Old->getDefinition() && !New->isThisDeclarationADefinition())
4424  UndefinedButUsed.insert(std::make_pair(Old->getCanonicalDecl(),
4425  SourceLocation()));
4426 
4427  if (New->getTLSKind() != Old->getTLSKind()) {
4428  if (!Old->getTLSKind()) {
4429  Diag(New->getLocation(), diag::err_thread_non_thread) << New->getDeclName();
4430  Diag(OldLocation, PrevDiag);
4431  } else if (!New->getTLSKind()) {
4432  Diag(New->getLocation(), diag::err_non_thread_thread) << New->getDeclName();
4433  Diag(OldLocation, PrevDiag);
4434  } else {
4435  // Do not allow redeclaration to change the variable between requiring
4436  // static and dynamic initialization.
4437  // FIXME: GCC allows this, but uses the TLS keyword on the first
4438  // declaration to determine the kind. Do we need to be compatible here?
4439  Diag(New->getLocation(), diag::err_thread_thread_different_kind)
4440  << New->getDeclName() << (New->getTLSKind() == VarDecl::TLS_Dynamic);
4441  Diag(OldLocation, PrevDiag);
4442  }
4443  }
4444 
4445  // C++ doesn't have tentative definitions, so go right ahead and check here.
4446  if (getLangOpts().CPlusPlus &&
4448  if (Old->isStaticDataMember() && Old->getCanonicalDecl()->isInline() &&
4449  Old->getCanonicalDecl()->isConstexpr()) {
4450  // This definition won't be a definition any more once it's been merged.
4451  Diag(New->getLocation(),
4452  diag::warn_deprecated_redundant_constexpr_static_def);
4453  } else if (VarDecl *Def = Old->getDefinition()) {
4454  if (checkVarDeclRedefinition(Def, New))
4455  return;
4456  }
4457  }
4458 
4459  if (haveIncompatibleLanguageLinkages(Old, New)) {
4460  Diag(New->getLocation(), diag::err_different_language_linkage) << New;
4461  Diag(OldLocation, PrevDiag);
4462  New->setInvalidDecl();
4463  return;
4464  }
4465 
4466  // Merge "used" flag.
4467  if (Old->getMostRecentDecl()->isUsed(false))
4468  New->setIsUsed();
4469 
4470  // Keep a chain of previous declarations.
4471  New->setPreviousDecl(Old);
4472  if (NewTemplate)
4473  NewTemplate->setPreviousDecl(OldTemplate);
4474 
4475  // Inherit access appropriately.
4476  New->setAccess(Old->getAccess());
4477  if (NewTemplate)
4478  NewTemplate->setAccess(New->getAccess());
4479 
4480  if (Old->isInline())
4481  New->setImplicitlyInline();
4482 }
4483 
4485  SourceManager &SrcMgr = getSourceManager();
4486  auto FNewDecLoc = SrcMgr.getDecomposedLoc(New);
4487  auto FOldDecLoc = SrcMgr.getDecomposedLoc(Old->getLocation());
4488  auto *FNew = SrcMgr.getFileEntryForID(FNewDecLoc.first);
4489  auto *FOld = SrcMgr.getFileEntryForID(FOldDecLoc.first);
4490  auto &HSI = PP.getHeaderSearchInfo();
4491  StringRef HdrFilename =
4492  SrcMgr.getFilename(SrcMgr.getSpellingLoc(Old->getLocation()));
4493 
4494  auto noteFromModuleOrInclude = [&](Module *Mod,
4495  SourceLocation IncLoc) -> bool {
4496  // Redefinition errors with modules are common with non modular mapped
4497  // headers, example: a non-modular header H in module A that also gets
4498  // included directly in a TU. Pointing twice to the same header/definition
4499  // is confusing, try to get better diagnostics when modules is on.
4500  if (IncLoc.isValid()) {
4501  if (Mod) {
4502  Diag(IncLoc, diag::note_redefinition_modules_same_file)
4503  << HdrFilename.str() << Mod->getFullModuleName();
4504  if (!Mod->DefinitionLoc.isInvalid())
4505  Diag(Mod->DefinitionLoc, diag::note_defined_here)
4506  << Mod->getFullModuleName();
4507  } else {
4508  Diag(IncLoc, diag::note_redefinition_include_same_file)
4509  << HdrFilename.str();
4510  }
4511  return true;
4512  }
4513 
4514  return false;
4515  };
4516 
4517  // Is it the same file and same offset? Provide more information on why
4518  // this leads to a redefinition error.
4519  if (FNew == FOld && FNewDecLoc.second == FOldDecLoc.second) {
4520  SourceLocation OldIncLoc = SrcMgr.getIncludeLoc(FOldDecLoc.first);
4521  SourceLocation NewIncLoc = SrcMgr.getIncludeLoc(FNewDecLoc.first);
4522  bool EmittedDiag =
4523  noteFromModuleOrInclude(Old->getOwningModule(), OldIncLoc);
4524  EmittedDiag |= noteFromModuleOrInclude(getCurrentModule(), NewIncLoc);
4525 
4526  // If the header has no guards, emit a note suggesting one.
4527  if (FOld && !HSI.isFileMultipleIncludeGuarded(FOld))
4528  Diag(Old->getLocation(), diag::note_use_ifdef_guards);
4529 
4530  if (EmittedDiag)
4531  return;
4532  }
4533 
4534  // Redefinition coming from different files or couldn't do better above.
4535  if (Old->getLocation().isValid())
4536  Diag(Old->getLocation(), diag::note_previous_definition);
4537 }
4538 
4539 /// We've just determined that \p Old and \p New both appear to be definitions
4540 /// of the same variable. Either diagnose or fix the problem.
4542  if (!hasVisibleDefinition(Old) &&
4543  (New->getFormalLinkage() == InternalLinkage ||
4544  New->isInline() ||
4545  New->getDescribedVarTemplate() ||
4547  New->getDeclContext()->isDependentContext())) {
4548  // The previous definition is hidden, and multiple definitions are
4549  // permitted (in separate TUs). Demote this to a declaration.
4551 
4552  // Make the canonical definition visible.
4553  if (auto *OldTD = Old->getDescribedVarTemplate())
4554  makeMergedDefinitionVisible(OldTD);
4555  makeMergedDefinitionVisible(Old);
4556  return false;
4557  } else {
4558  Diag(New->getLocation(), diag::err_redefinition) << New;
4559  notePreviousDefinition(Old, New->getLocation());
4560  New->setInvalidDecl();
4561  return true;
4562  }
4563 }
4564 
4565 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4566 /// no declarator (e.g. "struct foo;") is parsed.
4567 Decl *
4569  RecordDecl *&AnonRecord) {
4570  return ParsedFreeStandingDeclSpec(S, AS, DS, MultiTemplateParamsArg(), false,
4571  AnonRecord);
4572 }
4573 
4574 // The MS ABI changed between VS2013 and VS2015 with regard to numbers used to
4575 // disambiguate entities defined in different scopes.
4576 // While the VS2015 ABI fixes potential miscompiles, it is also breaks
4577 // compatibility.
4578 // We will pick our mangling number depending on which version of MSVC is being
4579 // targeted.
4580 static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S) {
4582  ? S->getMSCurManglingNumber()
4583  : S->getMSLastManglingNumber();
4584 }
4585 
4586 void Sema::handleTagNumbering(const TagDecl *Tag, Scope *TagScope) {
4587  if (!Context.getLangOpts().CPlusPlus)
4588  return;
4589 
4590  if (isa<CXXRecordDecl>(Tag->getParent())) {
4591  // If this tag is the direct child of a class, number it if
4592  // it is anonymous.
4593  if (!Tag->getName().empty() || Tag->getTypedefNameForAnonDecl())
4594  return;
4595  MangleNumberingContext &MCtx =
4596  Context.getManglingNumberContext(Tag->getParent());
4597  Context.setManglingNumber(
4598  Tag, MCtx.getManglingNumber(
4599  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4600  return;
4601  }
4602 
4603  // If this tag isn't a direct child of a class, number it if it is local.
4604  MangleNumberingContext *MCtx;
4605  Decl *ManglingContextDecl;
4606  std::tie(MCtx, ManglingContextDecl) =
4607  getCurrentMangleNumberContext(Tag->getDeclContext());
4608  if (MCtx) {
4609  Context.setManglingNumber(
4610  Tag, MCtx->getManglingNumber(
4611  Tag, getMSManglingNumber(getLangOpts(), TagScope)));
4612  }
4613 }
4614 
4615 namespace {
4616 struct NonCLikeKind {
4617  enum {
4618  None,
4619  BaseClass,
4620  DefaultMemberInit,
4621  Lambda,
4622  Friend,
4623  OtherMember,
4624  Invalid,
4625  } Kind = None;
4626  SourceRange Range;
4627 
4628  explicit operator bool() { return Kind != None; }
4629 };
4630 }
4631 
4632 /// Determine whether a class is C-like, according to the rules of C++
4633 /// [dcl.typedef] for anonymous classes with typedef names for linkage.
4634 static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD) {
4635  if (RD->isInvalidDecl())
4636  return {NonCLikeKind::Invalid, {}};
4637 
4638  // C++ [dcl.typedef]p9: [P1766R1]
4639  // An unnamed class with a typedef name for linkage purposes shall not
4640  //
4641  // -- have any base classes
4642  if (RD->getNumBases())
4643  return {NonCLikeKind::BaseClass,
4645  RD->bases_end()[-1].getEndLoc())};
4646  bool Invalid = false;
4647  for (Decl *D : RD->decls()) {
4648  // Don't complain about things we already diagnosed.
4649  if (D->isInvalidDecl()) {
4650  Invalid = true;
4651  continue;
4652  }
4653 
4654  // -- have any [...] default member initializers
4655  if (auto *FD = dyn_cast<FieldDecl>(D)) {
4656  if (FD->hasInClassInitializer()) {
4657  auto *Init = FD->getInClassInitializer();
4658  return {NonCLikeKind::DefaultMemberInit,
4659  Init ? Init->getSourceRange() : D->getSourceRange()};
4660  }
4661  continue;
4662  }
4663 
4664  // FIXME: We don't allow friend declarations. This violates the wording of
4665  // P1766, but not the intent.
4666  if (isa<FriendDecl>(D))
4667  return {NonCLikeKind::Friend, D->getSourceRange()};
4668 
4669  // -- declare any members other than non-static data members, member
4670  // enumerations, or member classes,
4671  if (isa<StaticAssertDecl>(D) || isa<IndirectFieldDecl>(D) ||
4672  isa<EnumDecl>(D))
4673  continue;
4674  auto *MemberRD = dyn_cast<CXXRecordDecl>(D);
4675  if (!MemberRD) {
4676  if (D->isImplicit())
4677  continue;
4678  return {NonCLikeKind::OtherMember, D->getSourceRange()};
4679  }
4680 
4681  // -- contain a lambda-expression,
4682  if (MemberRD->isLambda())
4683  return {NonCLikeKind::Lambda, MemberRD->getSourceRange()};
4684 
4685  // and all member classes shall also satisfy these requirements
4686  // (recursively).
4687  if (MemberRD->isThisDeclarationADefinition()) {
4688  if (auto Kind = getNonCLikeKindForAnonymousStruct(MemberRD))
4689  return Kind;
4690  }
4691  }
4692 
4693  return {Invalid ? NonCLikeKind::Invalid : NonCLikeKind::None, {}};
4694 }
4695 
4697  TypedefNameDecl *NewTD) {
4698  if (TagFromDeclSpec->isInvalidDecl())
4699  return;
4700 
4701  // Do nothing if the tag already has a name for linkage purposes.
4702  if (TagFromDeclSpec->hasNameForLinkage())
4703  return;
4704 
4705  // A well-formed anonymous tag must always be a TUK_Definition.
4706  assert(TagFromDeclSpec->isThisDeclarationADefinition());
4707 
4708  // The type must match the tag exactly; no qualifiers allowed.
4709  if (!Context.hasSameType(NewTD->getUnderlyingType(),
4710  Context.getTagDeclType(TagFromDeclSpec))) {
4711  if (getLangOpts().CPlusPlus)
4712  Context.addTypedefNameForUnnamedTagDecl(TagFromDeclSpec, NewTD);
4713  return;
4714  }
4715 
4716  // C++ [dcl.typedef]p9: [P1766R1, applied as DR]
4717  // An unnamed class with a typedef name for linkage purposes shall [be
4718  // C-like].
4719  //
4720  // FIXME: Also diagnose if we've already computed the linkage. That ideally
4721  // shouldn't happen, but there are constructs that the language rule doesn't
4722  // disallow for which we can't reasonably avoid computing linkage early.
4723  const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TagFromDeclSpec);
4724  NonCLikeKind NonCLike = RD ? getNonCLikeKindForAnonymousStruct(RD)
4725  : NonCLikeKind();
4726  bool ChangesLinkage = TagFromDeclSpec->hasLinkageBeenComputed();
4727  if (NonCLike || ChangesLinkage) {
4728  if (NonCLike.Kind == NonCLikeKind::Invalid)
4729  return;
4730 
4731  unsigned DiagID = diag::ext_non_c_like_anon_struct_in_typedef;
4732  if (ChangesLinkage) {
4733  // If the linkage changes, we can't accept this as an extension.
4734  if (NonCLike.Kind == NonCLikeKind::None)
4735  DiagID = diag::err_typedef_changes_linkage;
4736  else
4737  DiagID = diag::err_non_c_like_anon_struct_in_typedef;
4738  }
4739 
4740  SourceLocation FixitLoc =
4741  getLocForEndOfToken(TagFromDeclSpec->getInnerLocStart());
4742  llvm::SmallString<40> TextToInsert;
4743  TextToInsert += ' ';
4744  TextToInsert += NewTD->getIdentifier()->getName();
4745 
4746  Diag(FixitLoc, DiagID)
4747  << isa<TypeAliasDecl>(NewTD)
4748  << FixItHint::CreateInsertion(FixitLoc, TextToInsert);
4749  if (NonCLike.Kind != NonCLikeKind::None) {
4750  Diag(NonCLike.Range.getBegin(), diag::note_non_c_like_anon_struct)
4751  << NonCLike.Kind - 1 << NonCLike.Range;
4752  }
4753  Diag(NewTD->getLocation(), diag::note_typedef_for_linkage_here)
4754  << NewTD << isa<TypeAliasDecl>(NewTD);
4755 
4756  if (ChangesLinkage)
4757  return;
4758  }
4759 
4760  // Otherwise, set this as the anon-decl typedef for the tag.
4761  TagFromDeclSpec->setTypedefNameForAnonDecl(NewTD);
4762 }
4763 
4765  switch (T) {
4766  case DeclSpec::TST_class:
4767  return 0;
4768  case DeclSpec::TST_struct:
4769  return 1;
4771  return 2;
4772  case DeclSpec::TST_union:
4773  return 3;
4774  case DeclSpec::TST_enum:
4775  return 4;
4776  default:
4777  llvm_unreachable("unexpected type specifier");
4778  }
4779 }
4780 
4781 /// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
4782 /// no declarator (e.g. "struct foo;") is parsed. It also accepts template
4783 /// parameters to cope with template friend declarations.
4784 Decl *
4786  MultiTemplateParamsArg TemplateParams,
4787  bool IsExplicitInstantiation,
4788  RecordDecl *&AnonRecord) {
4789  Decl *TagD = nullptr;
4790  TagDecl *Tag = nullptr;
4791  if (DS.getTypeSpecType() == DeclSpec::TST_class ||
4796  TagD = DS.getRepAsDecl();
4797 
4798  if (!TagD) // We probably had an error
4799  return nullptr;
4800 
4801  // Note that the above type specs guarantee that the
4802  // type rep is a Decl, whereas in many of the others
4803  // it's a Type.
4804  if (isa<TagDecl>(TagD))
4805  Tag = cast<TagDecl>(TagD);
4806  else if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(TagD))
4807  Tag = CTD->getTemplatedDecl();
4808  }
4809 
4810  if (Tag) {
4811  handleTagNumbering(Tag, S);
4812  Tag->setFreeStanding();
4813  if (Tag->isInvalidDecl())
4814  return Tag;
4815  }
4816 
4817  if (unsigned TypeQuals = DS.getTypeQualifiers()) {
4818  // Enforce C99 6.7.3p2: "Types other than pointer types derived from object
4819  // or incomplete types shall not be restrict-qualified."
4820  if (TypeQuals & DeclSpec::TQ_restrict)
4821  Diag(DS.getRestrictSpecLoc(),
4822  diag::err_typecheck_invalid_restrict_not_pointer_noarg)
4823  << DS.getSourceRange();
4824  }
4825 
4826  if (DS.isInlineSpecified())
4827  Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4828  << getLangOpts().CPlusPlus17;
4829 
4830  if (DS.hasConstexprSpecifier()) {
4831  // C++0x [dcl.constexpr]p1: constexpr can only be applied to declarations
4832  // and definitions of functions and variables.
4833  // C++2a [dcl.constexpr]p1: The consteval specifier shall be applied only to
4834  // the declaration of a function or function template
4835  if (Tag)
4836  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_tag)
4838  << static_cast<int>(DS.getConstexprSpecifier());
4839  else
4840  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_wrong_decl_kind)
4841  << static_cast<int>(DS.getConstexprSpecifier());
4842  // Don't emit warnings after this error.
4843  return TagD;
4844  }
4845 
4846  DiagnoseFunctionSpecifiers(DS);
4847 
4848  if (DS.isFriendSpecified()) {
4849  // If we're dealing with a decl but not a TagDecl, assume that
4850  // whatever routines created it handled the friendship aspect.
4851  if (TagD && !Tag)
4852  return nullptr;
4853  return ActOnFriendTypeDecl(S, DS, TemplateParams);
4854  }
4855 
4856  const CXXScopeSpec &SS = DS.getTypeSpecScope();
4857  bool IsExplicitSpecialization =
4858  !TemplateParams.empty() && TemplateParams.back()->size() == 0;
4859  if (Tag && SS.isNotEmpty() && !Tag->isCompleteDefinition() &&
4860  !IsExplicitInstantiation && !IsExplicitSpecialization &&
4861  !isa<ClassTemplatePartialSpecializationDecl>(Tag)) {
4862  // Per C++ [dcl.type.elab]p1, a class declaration cannot have a
4863  // nested-name-specifier unless it is an explicit instantiation
4864  // or an explicit specialization.
4865  //
4866  // FIXME: We allow class template partial specializations here too, per the
4867  // obvious intent of DR1819.
4868  //
4869  // Per C++ [dcl.enum]p1, an opaque-enum-declaration can't either.
4870  Diag(SS.getBeginLoc(), diag::err_standalone_class_nested_name_specifier)
4872  return nullptr;
4873  }
4874 
4875  // Track whether this decl-specifier declares anything.
4876  bool DeclaresAnything = true;
4877 
4878  // Handle anonymous struct definitions.
4879  if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
4880  if (!Record->getDeclName() && Record->isCompleteDefinition() &&
4882  if (getLangOpts().CPlusPlus ||
4883  Record->getDeclContext()->isRecord()) {
4884  // If CurContext is a DeclContext that can contain statements,
4885  // RecursiveASTVisitor won't visit the decls that
4886  // BuildAnonymousStructOrUnion() will put into CurContext.
4887  // Also store them here so that they can be part of the
4888  // DeclStmt that gets created in this case.
4889  // FIXME: Also return the IndirectFieldDecls created by
4890  // BuildAnonymousStructOr union, for the same reason?
4891  if (CurContext->isFunctionOrMethod())
4892  AnonRecord = Record;
4893  return BuildAnonymousStructOrUnion(S, DS, AS, Record,
4894  Context.getPrintingPolicy());
4895  }
4896 
4897  DeclaresAnything = false;
4898  }
4899  }
4900 
4901  // C11 6.7.2.1p2:
4902  // A struct-declaration that does not declare an anonymous structure or
4903  // anonymous union shall contain a struct-declarator-list.
4904  //
4905  // This rule also existed in C89 and C99; the grammar for struct-declaration
4906  // did not permit a struct-declaration without a struct-declarator-list.
4907  if (!getLangOpts().CPlusPlus && CurContext->isRecord() &&
4909  // Check for Microsoft C extension: anonymous struct/union member.
4910  // Handle 2 kinds of anonymous struct/union:
4911  // struct STRUCT;
4912  // union UNION;
4913  // and
4914  // STRUCT_TYPE; <- where STRUCT_TYPE is a typedef struct.
4915  // UNION_TYPE; <- where UNION_TYPE is a typedef union.
4916  if ((Tag && Tag->getDeclName()) ||
4918  RecordDecl *Record = nullptr;
4919  if (Tag)
4920  Record = dyn_cast<RecordDecl>(Tag);
4921  else if (const RecordType *RT =
4923  Record = RT->getDecl();
4924  else if (const RecordType *UT = DS.getRepAsType().get()->getAsUnionType())
4925  Record = UT->getDecl();
4926 
4927  if (Record && getLangOpts().MicrosoftExt) {
4928  Diag(DS.getBeginLoc(), diag::ext_ms_anonymous_record)
4929  << Record->isUnion() << DS.getSourceRange();
4930  return BuildMicrosoftCAnonymousStruct(S, DS, Record);
4931  }
4932 
4933  DeclaresAnything = false;
4934  }
4935  }
4936 
4937  // Skip all the checks below if we have a type error.
4938  if (DS.getTypeSpecType() == DeclSpec::TST_error ||
4939  (TagD && TagD->isInvalidDecl()))
4940  return TagD;
4941 
4942  if (getLangOpts().CPlusPlus &&
4944  if (EnumDecl *Enum = dyn_cast_or_null<EnumDecl>(Tag))
4945  if (Enum->enumerator_begin() == Enum->enumerator_end() &&
4946  !Enum->getIdentifier() && !Enum->isInvalidDecl())
4947  DeclaresAnything = false;
4948 
4949  if (!DS.isMissingDeclaratorOk()) {
4950  // Customize diagnostic for a typedef missing a name.
4952  Diag(DS.getBeginLoc(), diag::ext_typedef_without_a_name)
4953  << DS.getSourceRange();
4954  else
4955  DeclaresAnything = false;
4956  }
4957 
4958  if (DS.isModulePrivateSpecified() &&
4959  Tag && Tag->getDeclContext()->isFunctionOrMethod())
4960  Diag(DS.getModulePrivateSpecLoc(), diag::err_module_private_local_class)
4961  << Tag->getTagKind()
4963 
4964  ActOnDocumentableDecl(TagD);
4965 
4966  // C 6.7/2:
4967  // A declaration [...] shall declare at least a declarator [...], a tag,
4968  // or the members of an enumeration.
4969  // C++ [dcl.dcl]p3:
4970  // [If there are no declarators], and except for the declaration of an
4971  // unnamed bit-field, the decl-specifier-seq shall introduce one or more
4972  // names into the program, or shall redeclare a name introduced by a
4973  // previous declaration.
4974  if (!DeclaresAnything) {
4975  // In C, we allow this as a (popular) extension / bug. Don't bother
4976  // producing further diagnostics for redundant qualifiers after this.
4977  Diag(DS.getBeginLoc(), (IsExplicitInstantiation || !TemplateParams.empty())
4978  ? diag::err_no_declarators
4979  : diag::ext_no_declarators)
4980  << DS.getSourceRange();
4981  return TagD;
4982  }
4983 
4984  // C++ [dcl.stc]p1:
4985  // If a storage-class-specifier appears in a decl-specifier-seq, [...] the
4986  // init-declarator-list of the declaration shall not be empty.
4987  // C++ [dcl.fct.spec]p1:
4988  // If a cv-qualifier appears in a decl-specifier-seq, the
4989  // init-declarator-list of the declaration shall not be empty.
4990  //
4991  // Spurious qualifiers here appear to be valid in C.
4992  unsigned DiagID = diag::warn_standalone_specifier;
4993  if (getLangOpts().CPlusPlus)
4994  DiagID = diag::ext_standalone_specifier;
4995 
4996  // Note that a linkage-specification sets a storage class, but
4997  // 'extern "C" struct foo;' is actually valid and not theoretically
4998  // useless.
4999  if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5000  if (SCS == DeclSpec::SCS_mutable)
5001  // Since mutable is not a viable storage class specifier in C, there is
5002  // no reason to treat it as an extension. Instead, diagnose as an error.
5003  Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_nonmember);
5004  else if (!DS.isExternInLinkageSpec() && SCS != DeclSpec::SCS_typedef)
5005  Diag(DS.getStorageClassSpecLoc(), DiagID)
5007  }
5008 
5009  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
5010  Diag(DS.getThreadStorageClassSpecLoc(), DiagID)
5011  << DeclSpec::getSpecifierName(TSCS);
5012  if (DS.getTypeQualifiers()) {
5014  Diag(DS.getConstSpecLoc(), DiagID) << "const";
5016  Diag(DS.getConstSpecLoc(), DiagID) << "volatile";
5017  // Restrict is covered above.
5019  Diag(DS.getAtomicSpecLoc(), DiagID) << "_Atomic";
5021  Diag(DS.getUnalignedSpecLoc(), DiagID) << "__unaligned";
5022  }
5023 
5024  // Warn about ignored type attributes, for example:
5025  // __attribute__((aligned)) struct A;
5026  // Attributes should be placed after tag to apply to type declaration.
5027  if (!DS.getAttributes().empty()) {
5028  DeclSpec::TST TypeSpecType = DS.getTypeSpecType();
5029  if (TypeSpecType == DeclSpec::TST_class ||
5030  TypeSpecType == DeclSpec::TST_struct ||
5031  TypeSpecType == DeclSpec::TST_interface ||
5032  TypeSpecType == DeclSpec::TST_union ||
5033  TypeSpecType == DeclSpec::TST_enum) {
5034  for (const ParsedAttr &AL : DS.getAttributes())
5035  Diag(AL.getLoc(), diag::warn_declspec_attribute_ignored)
5036  << AL << GetDiagnosticTypeSpecifierID(TypeSpecType);
5037  }
5038  }
5039 
5040  return TagD;
5041 }
5042 
5043 /// We are trying to inject an anonymous member into the given scope;
5044 /// check if there's an existing declaration that can't be overloaded.
5045 ///
5046 /// \return true if this is a forbidden redeclaration
5047 static bool CheckAnonMemberRedeclaration(Sema &SemaRef,
5048  Scope *S,
5049  DeclContext *Owner,
5050  DeclarationName Name,
5051  SourceLocation NameLoc,
5052  bool IsUnion) {
5053  LookupResult R(SemaRef, Name, NameLoc, Sema::LookupMemberName,
5055  if (!SemaRef.LookupName(R, S)) return false;
5056 
5057  // Pick a representative declaration.
5059  assert(PrevDecl && "Expected a non-null Decl");
5060 
5061  if (!SemaRef.isDeclInScope(PrevDecl, Owner, S))
5062  return false;
5063 
5064  SemaRef.Diag(NameLoc, diag::err_anonymous_record_member_redecl)
5065  << IsUnion << Name;
5066  SemaRef.Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
5067 
5068  return true;
5069 }
5070 
5071 /// InjectAnonymousStructOrUnionMembers - Inject the members of the
5072 /// anonymous struct or union AnonRecord into the owning context Owner
5073 /// and scope S. This routine will be invoked just after we realize
5074 /// that an unnamed union or struct is actually an anonymous union or
5075 /// struct, e.g.,
5076 ///
5077 /// @code
5078 /// union {
5079 /// int i;
5080 /// float f;
5081 /// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
5082 /// // f into the surrounding scope.x
5083 /// @endcode
5084 ///
5085 /// This routine is recursive, injecting the names of nested anonymous
5086 /// structs/unions into the owning context and scope as well.
5087 static bool
5089  RecordDecl *AnonRecord, AccessSpecifier AS,
5090  SmallVectorImpl<NamedDecl *> &Chaining) {
5091  bool Invalid = false;
5092 
5093  // Look every FieldDecl and IndirectFieldDecl with a name.
5094  for (auto *D : AnonRecord->decls()) {
5095  if ((isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D)) &&
5096  cast<NamedDecl>(D)->getDeclName()) {
5097  ValueDecl *VD = cast<ValueDecl>(D);
5098  if (CheckAnonMemberRedeclaration(SemaRef, S, Owner, VD->getDeclName(),
5099  VD->getLocation(),
5100  AnonRecord->isUnion())) {
5101  // C++ [class.union]p2:
5102  // The names of the members of an anonymous union shall be
5103  // distinct from the names of any other entity in the
5104  // scope in which the anonymous union is declared.
5105  Invalid = true;
5106  } else {
5107  // C++ [class.union]p2:
5108  // For the purpose of name lookup, after the anonymous union
5109  // definition, the members of the anonymous union are
5110  // considered to have been defined in the scope in which the
5111  // anonymous union is declared.
5112  unsigned OldChainingSize = Chaining.size();
5113  if (IndirectFieldDecl *IF = dyn_cast<IndirectFieldDecl>(VD))
5114  Chaining.append(IF->chain_begin(), IF->chain_end());
5115  else
5116  Chaining.push_back(VD);
5117 
5118  assert(Chaining.size() >= 2);
5119  NamedDecl **NamedChain =
5120  new (SemaRef.Context)NamedDecl*[Chaining.size()];
5121  for (unsigned i = 0; i < Chaining.size(); i++)
5122  NamedChain[i] = Chaining[i];
5123 
5125  SemaRef.Context, Owner, VD->getLocation(), VD->getIdentifier(),
5126  VD->getType(), {NamedChain, Chaining.size()});
5127 
5128  for (const auto *Attr : VD->attrs())
5129  IndirectField->addAttr(Attr->clone(SemaRef.Context));
5130 
5131  IndirectField->setAccess(AS);
5132  IndirectField->setImplicit();
5133  SemaRef.PushOnScopeChains(IndirectField, S);
5134 
5135  // That includes picking up the appropriate access specifier.
5136  if (AS != AS_none) IndirectField->setAccess(AS);
5137 
5138  Chaining.resize(OldChainingSize);
5139  }
5140  }
5141  }
5142 
5143  return Invalid;
5144 }
5145 
5146 /// StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to
5147 /// a VarDecl::StorageClass. Any error reporting is up to the caller:
5148 /// illegal input values are mapped to SC_None.
5149 static StorageClass
5151  DeclSpec::SCS StorageClassSpec = DS.getStorageClassSpec();
5152  assert(StorageClassSpec != DeclSpec::SCS_typedef &&
5153  "Parser allowed 'typedef' as storage class VarDecl.");
5154  switch (StorageClassSpec) {
5155  case DeclSpec::SCS_unspecified: return SC_None;
5156  case DeclSpec::SCS_extern:
5157  if (DS.isExternInLinkageSpec())
5158  return SC_None;
5159  return SC_Extern;
5160  case DeclSpec::SCS_static: return SC_Static;
5161  case DeclSpec::SCS_auto: return SC_Auto;
5162  case DeclSpec::SCS_register: return SC_Register;
5164  // Illegal SCSs map to None: error reporting is up to the caller.
5165  case DeclSpec::SCS_mutable: // Fall through.
5166  case DeclSpec::SCS_typedef: return SC_None;
5167  }
5168  llvm_unreachable("unknown storage class specifier");
5169 }
5170 
5172  assert(Record->hasInClassInitializer());
5173 
5174  for (const auto *I : Record->decls()) {
5175  const auto *FD = dyn_cast<FieldDecl>(I);
5176  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
5177  FD = IFD->getAnonField();
5178  if (FD && FD->hasInClassInitializer())
5179  return FD->getLocation();
5180  }
5181 
5182  llvm_unreachable("couldn't find in-class initializer");
5183 }
5184 
5186  SourceLocation DefaultInitLoc) {
5187  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5188  return;
5189 
5190  S.Diag(DefaultInitLoc, diag::err_multiple_mem_union_initialization);
5191  S.Diag(findDefaultInitializer(Parent), diag::note_previous_initializer) << 0;
5192 }
5193 
5195  CXXRecordDecl *AnonUnion) {
5196  if (!Parent->isUnion() || !Parent->hasInClassInitializer())
5197  return;
5198 
5200 }
5201 
5202 /// BuildAnonymousStructOrUnion - Handle the declaration of an
5203 /// anonymous structure or union. Anonymous unions are a C++ feature
5204 /// (C++ [class.union]) and a C11 feature; anonymous structures
5205 /// are a C11 feature and GNU C++ extension.
5207  AccessSpecifier AS,
5208  RecordDecl *Record,
5209  const PrintingPolicy &Policy) {
5210  DeclContext *Owner = Record->getDeclContext();
5211 
5212  // Diagnose whether this anonymous struct/union is an extension.
5213  if (Record->isUnion() && !getLangOpts().CPlusPlus && !getLangOpts().C11)
5214  Diag(Record->getLocation(), diag::ext_anonymous_union);
5215  else if (!Record->isUnion() && getLangOpts().CPlusPlus)
5216  Diag(Record->getLocation(), diag::ext_gnu_anonymous_struct);
5217  else if (!Record->isUnion() && !getLangOpts().C11)
5218  Diag(Record->getLocation(), diag::ext_c11_anonymous_struct);
5219 
5220  // C and C++ require different kinds of checks for anonymous
5221  // structs/unions.
5222  bool Invalid = false;
5223  if (getLangOpts().CPlusPlus) {
5224  const char *PrevSpec = nullptr;
5225  if (Record->isUnion()) {
5226  // C++ [class.union]p6:
5227  // C++17 [class.union.anon]p2:
5228  // Anonymous unions declared in a named namespace or in the
5229  // global namespace shall be declared static.
5230  unsigned DiagID;
5231  DeclContext *OwnerScope = Owner->getRedeclContext();
5233  (OwnerScope->isTranslationUnit() ||
5234  (OwnerScope->isNamespace() &&
5235  !cast<NamespaceDecl>(OwnerScope)->isAnonymousNamespace()))) {
5236  Diag(Record->getLocation(), diag::err_anonymous_union_not_static)
5237  << FixItHint::CreateInsertion(Record->getLocation(), "static ");
5238 
5239  // Recover by adding 'static'.
5241  PrevSpec, DiagID, Policy);
5242  }
5243  // C++ [class.union]p6:
5244  // A storage class is not allowed in a declaration of an
5245  // anonymous union in a class scope.
5247  isa<RecordDecl>(Owner)) {
5249  diag::err_anonymous_union_with_storage_spec)
5251 
5252  // Recover by removing the storage specifier.
5254  SourceLocation(),
5255  PrevSpec, DiagID, Context.getPrintingPolicy());
5256  }
5257  }
5258 
5259  // Ignore const/volatile/restrict qualifiers.
5260  if (DS.getTypeQualifiers()) {
5262  Diag(DS.getConstSpecLoc(), diag::ext_anonymous_struct_union_qualified)
5263  << Record->isUnion() << "const"
5266  Diag(DS.getVolatileSpecLoc(),
5267  diag::ext_anonymous_struct_union_qualified)
5268  << Record->isUnion() << "volatile"
5271  Diag(DS.getRestrictSpecLoc(),
5272  diag::ext_anonymous_struct_union_qualified)
5273  << Record->isUnion() << "restrict"
5276  Diag(DS.getAtomicSpecLoc(),
5277  diag::ext_anonymous_struct_union_qualified)
5278  << Record->isUnion() << "_Atomic"
5282  diag::ext_anonymous_struct_union_qualified)
5283  << Record->isUnion() << "__unaligned"
5285 
5286  DS.ClearTypeQualifiers();
5287  }
5288 
5289  // C++ [class.union]p2:
5290  // The member-specification of an anonymous union shall only
5291  // define non-static data members. [Note: nested types and
5292  // functions cannot be declared within an anonymous union. ]
5293  for (auto *Mem : Record->decls()) {
5294  // Ignore invalid declarations; we already diagnosed them.
5295  if (Mem->isInvalidDecl())
5296  continue;
5297 
5298  if (auto *FD = dyn_cast<FieldDecl>(Mem)) {
5299  // C++ [class.union]p3:
5300  // An anonymous union shall not have private or protected
5301  // members (clause 11).
5302  assert(FD->getAccess() != AS_none);
5303  if (FD->getAccess() != AS_public) {
5304  Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
5305  << Record->isUnion() << (FD->getAccess() == AS_protected);
5306  Invalid = true;
5307  }
5308 
5309  // C++ [class.union]p1
5310  // An object of a class with a non-trivial constructor, a non-trivial
5311  // copy constructor, a non-trivial destructor, or a non-trivial copy
5312  // assignment operator cannot be a member of a union, nor can an
5313  // array of such objects.
5314  if (CheckNontrivialField(FD))
5315  Invalid = true;
5316  } else if (Mem->isImplicit()) {
5317  // Any implicit members are fine.
5318  } else if (isa<TagDecl>(Mem) && Mem->getDeclContext() != Record) {
5319  // This is a type that showed up in an
5320  // elaborated-type-specifier inside the anonymous struct or
5321  // union, but which actually declares a type outside of the
5322  // anonymous struct or union. It's okay.
5323  } else if (auto *MemRecord = dyn_cast<RecordDecl>(Mem)) {
5324  if (!MemRecord->isAnonymousStructOrUnion() &&
5325  MemRecord->getDeclName()) {
5326  // Visual C++ allows type definition in anonymous struct or union.
5327  if (getLangOpts().MicrosoftExt)
5328  Diag(MemRecord->getLocation(), diag::ext_anonymous_record_with_type)
5329  << Record->isUnion();
5330  else {
5331  // This is a nested type declaration.
5332  Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
5333  << Record->isUnion();
5334  Invalid = true;
5335  }
5336  } else {
5337  // This is an anonymous type definition within another anonymous type.
5338  // This is a popular extension, provided by Plan9, MSVC and GCC, but
5339  // not part of standard C++.
5340  Diag(MemRecord->getLocation(),
5341  diag::ext_anonymous_record_with_anonymous_type)
5342  << Record->isUnion();
5343  }
5344  } else if (isa<AccessSpecDecl>(Mem)) {
5345  // Any access specifier is fine.
5346  } else if (isa<StaticAssertDecl>(Mem)) {
5347  // In C++1z, static_assert declarations are also fine.
5348  } else {
5349  // We have something that isn't a non-static data
5350  // member. Complain about it.
5351  unsigned DK = diag::err_anonymous_record_bad_member;
5352  if (isa<TypeDecl>(Mem))
5353  DK = diag::err_anonymous_record_with_type;
5354  else if (isa<FunctionDecl>(Mem))
5355  DK = diag::err_anonymous_record_with_function;
5356  else if (isa<VarDecl>(Mem))
5357  DK = diag::err_anonymous_record_with_static;
5358 
5359  // Visual C++ allows type definition in anonymous struct or union.
5360  if (getLangOpts().MicrosoftExt &&
5361  DK == diag::err_anonymous_record_with_type)
5362  Diag(Mem->getLocation(), diag::ext_anonymous_record_with_type)
5363  << Record->isUnion();
5364  else {
5365  Diag(Mem->getLocation(), DK) << Record->isUnion();
5366  Invalid = true;
5367  }
5368  }
5369  }
5370 
5371  // C++11 [class.union]p8 (DR1460):
5372  // At most one variant member of a union may have a
5373  // brace-or-equal-initializer.
5374  if (cast<CXXRecordDecl>(Record)->hasInClassInitializer() &&
5375  Owner->isRecord())
5376  checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Owner),
5377  cast<CXXRecordDecl>(Record));
5378  }
5379 
5380  if (!Record->isUnion() && !Owner->isRecord()) {
5381  Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
5382  << getLangOpts().CPlusPlus;
5383  Invalid = true;
5384  }
5385 
5386  // C++ [dcl.dcl]p3:
5387  // [If there are no declarators], and except for the declaration of an
5388  // unnamed bit-field, the decl-specifier-seq shall introduce one or more
5389  // names into the program
5390  // C++ [class.mem]p2:
5391  // each such member-declaration shall either declare at least one member
5392  // name of the class or declare at least one unnamed bit-field
5393  //
5394  // For C this is an error even for a named struct, and is diagnosed elsewhere.
5395  if (getLangOpts().CPlusPlus && Record->field_empty())
5396  Diag(DS.getBeginLoc(), diag::ext_no_declarators) << DS.getSourceRange();
5397 
5398  // Mock up a declarator.
5400  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5401  assert(TInfo && "couldn't build declarator info for anonymous struct/union");
5402 
5403  // Create a declaration for this anonymous struct/union.
5404  NamedDecl *Anon = nullptr;
5405  if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
5406  Anon = FieldDecl::Create(
5407  Context, OwningClass, DS.getBeginLoc(), Record->getLocation(),
5408  /*IdentifierInfo=*/nullptr, Context.getTypeDeclType(Record), TInfo,
5409  /*BitWidth=*/nullptr, /*Mutable=*/false,
5410  /*InitStyle=*/ICIS_NoInit);
5411  Anon->setAccess(AS);
5412  ProcessDeclAttributes(S, Anon, Dc);
5413 
5414  if (getLangOpts().CPlusPlus)
5415  FieldCollector->Add(cast<FieldDecl>(Anon));
5416  } else {
5417  DeclSpec::SCS SCSpec = DS.getStorageClassSpec();
5419  if (SCSpec == DeclSpec::SCS_mutable) {
5420  // mutable can only appear on non-static class members, so it's always
5421  // an error here
5422  Diag(Record->getLocation(), diag::err_mutable_nonmember);
5423  Invalid = true;
5424  SC = SC_None;
5425  }
5426 
5427  assert(DS.getAttributes().empty() && "No attribute expected");
5428  Anon = VarDecl::Create(Context, Owner, DS.getBeginLoc(),
5429  Record->getLocation(), /*IdentifierInfo=*/nullptr,
5430  Context.getTypeDeclType(Record), TInfo, SC);
5431 
5432  // Default-initialize the implicit variable. This initialization will be
5433  // trivial in almost all cases, except if a union member has an in-class
5434  // initializer:
5435  // union { int n = 0; };
5436  ActOnUninitializedDecl(Anon);
5437  }
5438  Anon->setImplicit();
5439 
5440  // Mark this as an anonymous struct/union type.
5441  Record->setAnonymousStructOrUnion(true);
5442 
5443  // Add the anonymous struct/union object to the current
5444  // context. We'll be referencing this object when we refer to one of
5445  // its members.
5446  Owner->addDecl(Anon);
5447 
5448  // Inject the members of the anonymous struct/union into the owning
5449  // context and into the identifier resolver chain for name lookup
5450  // purposes.
5452  Chain.push_back(Anon);
5453 
5454  if (InjectAnonymousStructOrUnionMembers(*this, S, Owner, Record, AS, Chain))
5455  Invalid = true;
5456 
5457  if (VarDecl *NewVD = dyn_cast<VarDecl>(Anon)) {
5458  if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
5459  MangleNumberingContext *MCtx;
5460  Decl *ManglingContextDecl;
5461  std::tie(MCtx, ManglingContextDecl) =
5462  getCurrentMangleNumberContext(NewVD->getDeclContext());
5463  if (MCtx) {
5464  Context.setManglingNumber(
5465  NewVD, MCtx->getManglingNumber(
5466  NewVD, getMSManglingNumber(getLangOpts(), S)));
5467  Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
5468  }
5469  }
5470  }
5471 
5472  if (Invalid)
5473  Anon->setInvalidDecl();
5474 
5475  return Anon;
5476 }
5477 
5478 /// BuildMicrosoftCAnonymousStruct - Handle the declaration of an
5479 /// Microsoft C anonymous structure.
5480 /// Ref: http://msdn.microsoft.com/en-us/library/z2cx9y4f.aspx
5481 /// Example:
5482 ///
5483 /// struct A { int a; };
5484 /// struct B { struct A; int b; };
5485 ///
5486 /// void foo() {
5487 /// B var;
5488 /// var.a = 3;
5489 /// }
5490 ///
5492  RecordDecl *Record) {
5493  assert(Record && "expected a record!");
5494 
5495  // Mock up a declarator.
5497  TypeSourceInfo *TInfo = GetTypeForDeclarator(Dc, S);
5498  assert(TInfo && "couldn't build declarator info for anonymous struct");
5499 
5500  auto *ParentDecl = cast<RecordDecl>(CurContext);
5501  QualType RecTy = Context.getTypeDeclType(Record);
5502 
5503  // Create a declaration for this anonymous struct.
5504  NamedDecl *Anon =
5505  FieldDecl::Create(Context, ParentDecl, DS.getBeginLoc(), DS.getBeginLoc(),
5506  /*IdentifierInfo=*/nullptr, RecTy, TInfo,
5507  /*BitWidth=*/nullptr, /*Mutable=*/false,
5508  /*InitStyle=*/ICIS_NoInit);
5509  Anon->setImplicit();
5510 
5511  // Add the anonymous struct object to the current context.
5512  CurContext->addDecl(Anon);
5513 
5514  // Inject the members of the anonymous struct into the current
5515  // context and into the identifier resolver chain for name lookup
5516  // purposes.
5518  Chain.push_back(Anon);
5519 
5520  RecordDecl *RecordDef = Record->getDefinition();
5521  if (RequireCompleteSizedType(Anon->getLocation(), RecTy,
5522  diag::err_field_incomplete_or_sizeless) ||
5523  InjectAnonymousStructOrUnionMembers(*this, S, CurContext, RecordDef,
5524  AS_none, Chain)) {
5525  Anon->setInvalidDecl();
5526  ParentDecl->setInvalidDecl();
5527  }
5528 
5529  return Anon;
5530 }
5531 
5532 /// GetNameForDeclarator - Determine the full declaration name for the
5533 /// given Declarator.
5535  return GetNameFromUnqualifiedId(D.getName());
5536 }
5537 
5538 /// Retrieves the declaration name from a parsed unqualified-id.
5541  DeclarationNameInfo NameInfo;
5542  NameInfo.setLoc(Name.StartLocation);
5543 
5544  switch (Name.getKind()) {
5545 
5548  NameInfo.setName(Name.Identifier);
5549  return NameInfo;
5550 
5552  // C++ [temp.deduct.guide]p3:
5553  // The simple-template-id shall name a class template specialization.
5554  // The template-name shall be the same identifier as the template-name
5555  // of the simple-template-id.
5556  // These together intend to imply that the template-name shall name a
5557  // class template.
5558  // FIXME: template<typename T> struct X {};
5559  // template<typename T> using Y = X<T>;
5560  // Y(int) -> Y<int>;
5561  // satisfies these rules but does not name a class template.
5562  TemplateName TN = Name.TemplateName.get().get();
5563  auto *Template = TN.getAsTemplateDecl();
5564  if (!Template || !isa<ClassTemplateDecl>(Template)) {
5565  Diag(Name.StartLocation,
5566  diag::err_deduction_guide_name_not_class_template)
5567  << (int)getTemplateNameKindForDiagnostics(TN) << TN;
5568  if (Template)
5569  Diag(Template->getLocation(), diag::note_template_decl_here);
5570  return DeclarationNameInfo();
5571  }
5572 
5573  NameInfo.setName(
5574  Context.DeclarationNames.getCXXDeductionGuideName(Template));
5575  return NameInfo;
5576  }
5577 
5579  NameInfo.setName(Context.DeclarationNames.getCXXOperatorName(
5580  Name.OperatorFunctionId.Operator));
5582  Name.OperatorFunctionId.SymbolLocations[0], Name.EndLocation));
5583  return NameInfo;
5584 
5587  Name.Identifier));
5588  NameInfo.setCXXLiteralOperatorNameLoc(Name.EndLocation);
5589  return NameInfo;
5590 
5592  TypeSourceInfo *TInfo;
5593  QualType Ty = GetTypeFromParser(Name.ConversionFunctionId, &TInfo);
5594  if (Ty.isNull())
5595  return DeclarationNameInfo();
5597  Context.getCanonicalType(Ty)));
5598  NameInfo.setNamedTypeInfo(TInfo);
5599  return NameInfo;
5600  }
5601 
5603  TypeSourceInfo *TInfo;
5604  QualType Ty = GetTypeFromParser(Name.ConstructorName, &TInfo);
5605  if (Ty.isNull())
5606  return DeclarationNameInfo();
5608  Context.getCanonicalType(Ty)));
5609  NameInfo.setNamedTypeInfo(TInfo);
5610  return NameInfo;
5611  }
5612 
5614  // In well-formed code, we can only have a constructor
5615  // template-id that refers to the current context, so go there
5616  // to find the actual type being constructed.
5617  CXXRecordDecl *CurClass = dyn_cast<CXXRecordDecl>(CurContext);
5618  if (!CurClass || CurClass->getIdentifier() != Name.TemplateId->Name)
5619  return DeclarationNameInfo();
5620 
5621  // Determine the type of the class being constructed.
5622  QualType CurClassType = Context.getTypeDeclType(CurClass);
5623 
5624  // FIXME: Check two things: that the template-id names the same type as
5625  // CurClassType, and that the template-id does not occur when the name
5626  // was qualified.
5627 
5629  Context.getCanonicalType(CurClassType)));
5630  // FIXME: should we retrieve TypeSourceInfo?
5631  NameInfo.setNamedTypeInfo(nullptr);
5632  return NameInfo;
5633  }
5634 
5636  TypeSourceInfo *TInfo;
5637  QualType Ty = GetTypeFromParser(Name.DestructorName, &TInfo);
5638  if (Ty.isNull())
5639  return DeclarationNameInfo();
5641  Context.getCanonicalType(Ty)));
5642  NameInfo.setNamedTypeInfo(TInfo);
5643  return NameInfo;
5644  }
5645 
5647  TemplateName TName = Name.TemplateId->Template.get();
5648  SourceLocation TNameLoc = Name.TemplateId->TemplateNameLoc;
5649  return Context.getNameForTemplate(TName, TNameLoc);
5650  }
5651 
5652  } // switch (Name.getKind())
5653 
5654  llvm_unreachable("Unknown name kind");
5655 }
5656 
5658  do {
5659  if (Ty->isPointerType() || Ty->isReferenceType())
5660  Ty = Ty->getPointeeType();
5661  else if (Ty->isArrayType())
5662  Ty = Ty->castAsArrayTypeUnsafe()->getElementType();
5663  else
5664  return Ty.withoutLocalFastQualifiers();
5665  } while (true);
5666 }
5667 
5668 /// hasSimilarParameters - Determine whether the C++ functions Declaration
5669 /// and Definition have "nearly" matching parameters. This heuristic is
5670 /// used to improve diagnostics in the case where an out-of-line function
5671 /// definition doesn't match any declaration within the class or namespace.
5672 /// Also sets Params to the list of indices to the parameters that differ
5673 /// between the declaration and the definition. If hasSimilarParameters
5674 /// returns true and Params is empty, then all of the parameters match.
5675 static bool hasSimilarParameters(ASTContext &Context,
5676  FunctionDecl *Declaration,
5677  FunctionDecl *Definition,
5678  SmallVectorImpl<unsigned> &Params) {
5679  Params.clear();
5680  if (Declaration->param_size() != Definition->param_size())
5681  return false;
5682  for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
5683  QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
5684  QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
5685 
5686  // The parameter types are identical
5687  if (Context.hasSameUnqualifiedType(DefParamTy, DeclParamTy))
5688  continue;
5689 
5690  QualType DeclParamBaseTy = getCoreType(DeclParamTy);
5691  QualType DefParamBaseTy = getCoreType(DefParamTy);
5692  const IdentifierInfo *DeclTyName = DeclParamBaseTy.getBaseTypeIdentifier();
5693  const IdentifierInfo *DefTyName = DefParamBaseTy.getBaseTypeIdentifier();
5694 
5695  if (Context.hasSameUnqualifiedType(DeclParamBaseTy, DefParamBaseTy) ||
5696  (DeclTyName && DeclTyName == DefTyName))
5697  Params.push_back(Idx);
5698  else // The two parameters aren't even close
5699  return false;
5700  }
5701 
5702  return true;
5703 }
5704 
5705 /// NeedsRebuildingInCurrentInstantiation - Checks whether the given
5706 /// declarator needs to be rebuilt in the current instantiation.
5707 /// Any bits of declarator which appear before the name are valid for
5708 /// consideration here. That's specifically the type in the decl spec
5709 /// and the base type in any member-pointer chunks.
5711  DeclarationName Name) {
5712  // The types we specifically need to rebuild are:
5713  // - typenames, typeofs, and decltypes
5714  // - types which will become injected class names
5715  // Of course, we also need to rebuild any type referencing such a
5716  // type. It's safest to just say "dependent", but we call out a
5717  // few cases here.
5718 
5719  DeclSpec &DS = D.getMutableDeclSpec();
5720  switch (DS.getTypeSpecType()) {
5724  case DeclSpec::TST_atomic: {
5725  // Grab the type from the parser.
5726  TypeSourceInfo *TSI = nullptr;
5727  QualType T = S.GetTypeFromParser(DS.getRepAsType(), &TSI);
5728  if (T.isNull() || !T->isInstantiationDependentType()) break;
5729 
5730  // Make sure there's a type source info. This isn't really much
5731  // of a waste; most dependent types should have type source info
5732  // attached already.
5733  if (!TSI)
5735 
5736  // Rebuild the type in the current instantiation.
5737  TSI = S.RebuildTypeInCurrentInstantiation(TSI, D.getIdentifierLoc(), Name);
5738  if (!TSI) return true;
5739 
5740  // Store the new type back in the decl spec.
5741  ParsedType LocType = S.CreateParsedType(TSI->getType(), TSI);
5742  DS.UpdateTypeRep(LocType);
5743  break;
5744  }
5745 
5747  case DeclSpec::TST_typeofExpr: {
5748  Expr *E = DS.getRepAsExpr();
5750  if (Result.isInvalid()) return true;
5751  DS.UpdateExprRep(Result.get());
5752  break;
5753  }
5754 
5755  default:
5756  // Nothing to do for these decl specs.
5757  break;
5758  }
5759 
5760  // It doesn't matter what order we do this in.
5761  for (unsigned I = 0, E = D.getNumTypeObjects(); I != E; ++I) {
5762  DeclaratorChunk &Chunk = D.getTypeObject(I);
5763 
5764  // The only type information in the declarator which can come
5765  // before the declaration name is the base type of a member
5766  // pointer.
5767  if (Chunk.Kind != DeclaratorChunk::MemberPointer)
5768  continue;
5769 
5770  // Rebuild the scope specifier in-place.
5771  CXXScopeSpec &SS = Chunk.Mem.Scope();
5773  return true;
5774  }
5775 
5776  return false;
5777 }
5778 
5779 /// Returns true if the declaration is declared in a system header or from a
5780 /// system macro.
5781 static bool isFromSystemHeader(SourceManager &SM, const Decl *D) {
5782  return SM.isInSystemHeader(D->getLocation()) ||
5783  SM.isInSystemMacro(D->getLocation());
5784 }
5785 
5787  // Avoid warning twice on the same identifier, and don't warn on redeclaration
5788  // of system decl.
5789  if (D->getPreviousDecl() || D->isImplicit())
5790  return;
5791  ReservedIdentifierStatus Status = D->isReserved(getLangOpts());
5792  if (Status != ReservedIdentifierStatus::NotReserved &&
5793  !isFromSystemHeader(Context.getSourceManager(), D)) {
5794  Diag(D->getLocation(), diag::warn_reserved_extern_symbol)
5795  << D << static_cast<int>(Status);
5796  }
5797 }
5798 
5801  Decl *Dcl = HandleDeclarator(S, D, MultiTemplateParamsArg());
5802 
5803  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer() &&
5804  Dcl && Dcl->getDeclContext()->isFileContext())
5806 
5807  return Dcl;
5808 }
5809 
5810 /// DiagnoseClassNameShadow - Implement C++ [class.mem]p13:
5811 /// If T is the name of a class, then each of the following shall have a
5812 /// name different from T:
5813 /// - every static data member of class T;
5814 /// - every member function of class T
5815 /// - every member of class T that is itself a type;
5816 /// \returns true if the declaration name violates these rules.
5818  DeclarationNameInfo NameInfo) {
5819  DeclarationName Name = NameInfo.getName();
5820 
5821  CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(DC);
5822  while (Record && Record->isAnonymousStructOrUnion())
5823  Record = dyn_cast<CXXRecordDecl>(Record->getParent());
5824  if (Record && Record->getIdentifier() && Record->getDeclName() == Name) {
5825  Diag(NameInfo.getLoc(), diag::err_member_name_of_class) << Name;
5826  return true;
5827  }
5828 
5829  return false;
5830 }
5831 
5832 /// Diagnose a declaration whose declarator-id has the given
5833 /// nested-name-specifier.
5834 ///
5835 /// \param SS The nested-name-specifier of the declarator-id.
5836 ///
5837 /// \param DC The declaration context to which the nested-name-specifier
5838 /// resolves.
5839 ///
5840 /// \param Name The name of the entity being declared.
5841 ///
5842 /// \param Loc The location of the name of the entity being declared.
5843 ///
5844 /// \param IsTemplateId Whether the name is a (simple-)template-id, and thus
5845 /// we're declaring an explicit / partial specialization / instantiation.
5846 ///
5847 /// \returns true if we cannot safely recover from this error, false otherwise.
5849  DeclarationName Name,
5850  SourceLocation Loc, bool IsTemplateId) {
5851  DeclContext *Cur = CurContext;
5852  while (isa<LinkageSpecDecl>(Cur) || isa<CapturedDecl>(Cur))
5853  Cur = Cur->getParent();
5854 
5855  // If the user provided a superfluous scope specifier that refers back to the
5856  // class in which the entity is already declared, diagnose and ignore it.
5857  //
5858  // class X {
5859  // void X::f();
5860  // };
5861  //
5862  // Note, it was once ill-formed to give redundant qualification in all
5863  // contexts, but that rule was removed by DR482.
5864  if (Cur->Equals(DC)) {
5865  if (Cur->isRecord()) {
5866  Diag(Loc, LangOpts.MicrosoftExt ? diag::warn_member_extra_qualification
5867  : diag::err_member_extra_qualification)
5868  << Name << FixItHint::CreateRemoval(SS.getRange());
5869  SS.clear();
5870  } else {
5871  Diag(Loc, diag::warn_namespace_member_extra_qualification) << Name;
5872  }
5873  return false;
5874  }
5875 
5876  // Check whether the qualifying scope encloses the scope of the original
5877  // declaration. For a template-id, we perform the checks in
5878  // CheckTemplateSpecializationScope.
5879  if (!Cur->Encloses(DC) && !IsTemplateId) {
5880  if (Cur->isRecord())
5881  Diag(Loc, diag::err_member_qualification)
5882  << Name << SS.getRange();
5883  else if (isa<TranslationUnitDecl>(DC))
5884  Diag(Loc, diag::err_invalid_declarator_global_scope)
5885  << Name << SS.getRange();
5886  else if (isa<FunctionDecl>(Cur))
5887  Diag(Loc, diag::err_invalid_declarator_in_function)
5888  << Name << SS.getRange();
5889  else if (isa<BlockDecl>(Cur))
5890  Diag(Loc, diag::err_invalid_declarator_in_block)
5891  << Name << SS.getRange();
5892  else if (isa<ExportDecl>(Cur)) {
5893  if (!isa<NamespaceDecl>(DC))
5894  Diag(Loc, diag::err_export_non_namespace_scope_name)
5895  << Name << SS.getRange();
5896  else
5897  // The cases that DC is not NamespaceDecl should be handled in
5898  // CheckRedeclarationExported.
5899  return false;
5900  } else
5901  Diag(Loc, diag::err_invalid_declarator_scope)
5902  << Name << cast<NamedDecl>(Cur) << cast<NamedDecl>(DC) << SS.getRange();
5903 
5904  return true;
5905  }
5906 
5907  if (Cur->isRecord()) {
5908  // Cannot qualify members within a class.
5909  Diag(Loc, diag::err_member_qualification)
5910  << Name << SS.getRange();
5911  SS.clear();
5912 
5913  // C++ constructors and destructors with incorrect scopes can break
5914  // our AST invariants by having the wrong underlying types. If
5915  // that's the case, then drop this declaration entirely.
5916  if ((Name.getNameKind() == DeclarationName::CXXConstructorName ||
5917  Name.getNameKind() == DeclarationName::CXXDestructorName) &&
5918  !Context.hasSameType(Name.getCXXNameType(),
5919  Context.getTypeDeclType(cast<CXXRecordDecl>(Cur))))
5920  return true;
5921 
5922  return false;
5923  }
5924 
5925  // C++11 [dcl.meaning]p1:
5926  // [...] "The nested-name-specifier of the qualified declarator-id shall
5927  // not begin with a decltype-specifer"
5928  NestedNameSpecifierLoc SpecLoc(SS.getScopeRep(), SS.location_data());
5929  while (SpecLoc.getPrefix())
5930  SpecLoc = SpecLoc.getPrefix();
5931  if (isa_and_nonnull<DecltypeType>(
5932  SpecLoc.getNestedNameSpecifier()->getAsType()))
5933  Diag(Loc, diag::err_decltype_in_declarator)
5934  << SpecLoc.getTypeLoc().getSourceRange();
5935 
5936  return false;
5937 }
5938 
5940  MultiTemplateParamsArg TemplateParamLists) {
5941  // TODO: consider using NameInfo for diagnostic.
5942  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
5943  DeclarationName Name = NameInfo.getName();
5944 
5945  // All of these full declarators require an identifier. If it doesn't have
5946  // one, the ParsedFreeStandingDeclSpec action should be used.
5947  if (D.isDecompositionDeclarator()) {
5948  return ActOnDecompositionDeclarator(S, D, TemplateParamLists);
5949  } else if (!Name) {
5950  if (!D.isInvalidType()) // Reject this if we think it is valid.
5951  Diag(D.getDeclSpec().getBeginLoc(), diag::err_declarator_need_ident)
5952  << D.getDeclSpec().getSourceRange() << D.getSourceRange();
5953  return nullptr;
5954  } else if (DiagnoseUnexpandedParameterPack(NameInfo, UPPC_DeclarationType))
5955  return nullptr;
5956 
5957  // The scope passed in may not be a decl scope. Zip up the scope tree until
5958  // we find one that is.
5959  while ((S->getFlags() & Scope::DeclScope) == 0 ||
5960  (S->getFlags() & Scope::TemplateParamScope) != 0)
5961  S = S->getParent();
5962 
5963  DeclContext *DC = CurContext;
5964  if (D.getCXXScopeSpec().isInvalid())
5965  D.setInvalidType();
5966  else if (D.getCXXScopeSpec().isSet()) {
5967  if (DiagnoseUnexpandedParameterPack(D.getCXXScopeSpec(),
5968  UPPC_DeclarationQualifier))
5969  return nullptr;
5970 
5971  bool EnteringContext = !D.getDeclSpec().isFriendSpecified();
5972  DC = computeDeclContext(D.getCXXScopeSpec(), EnteringContext);
5973  if (!DC || isa<EnumDecl>(DC)) {
5974  // If we could not compute the declaration context, it's because the
5975  // declaration context is dependent but does not refer to a class,
5976  // class template, or class template partial specialization. Complain
5977  // and return early, to avoid the coming semantic disaster.
5978  Diag(D.getIdentifierLoc(),
5979  diag::err_template_qualified_declarator_no_match)
5980  << D.getCXXScopeSpec().getScopeRep()
5981  << D.getCXXScopeSpec().getRange();
5982  return nullptr;
5983  }
5984  bool IsDependentContext = DC->isDependentContext();
5985 
5986  if (!IsDependentContext &&
5987  RequireCompleteDeclContext(D.getCXXScopeSpec(), DC))
5988  return nullptr;
5989 
5990  // If a class is incomplete, do not parse entities inside it.
5991  if (isa<CXXRecordDecl>(DC) && !cast<CXXRecordDecl>(DC)->hasDefinition()) {
5992  Diag(D.getIdentifierLoc(),
5993  diag::err_member_def_undefined_record)
5994  << Name << DC << D.getCXXScopeSpec().getRange();
5995  return nullptr;
5996  }
5997  if (!D.getDeclSpec().isFriendSpecified()) {
5998  if (diagnoseQualifiedDeclaration(
5999  D.getCXXScopeSpec(), DC, Name, D.getIdentifierLoc(),
6001  if (DC->isRecord())
6002  return nullptr;
6003 
6004  D.setInvalidType();
6005  }
6006  }
6007 
6008  // Check whether we need to rebuild the type of the given
6009  // declaration in the current instantiation.
6010  if (EnteringContext && IsDependentContext &&
6011  TemplateParamLists.size() != 0) {
6012  ContextRAII SavedContext(*this, DC);
6013  if (RebuildDeclaratorInCurrentInstantiation(*this, D, Name))
6014  D.setInvalidType();
6015  }
6016  }
6017 
6018  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
6019  QualType R = TInfo->getType();
6020 
6021  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
6022  UPPC_DeclarationType))
6023  D.setInvalidType();
6024 
6025  LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
6026  forRedeclarationInCurContext());
6027 
6028  // See if this is a redefinition of a variable in the same scope.
6029  if (!D.getCXXScopeSpec().isSet()) {
6030  bool IsLinkageLookup = false;
6031  bool CreateBuiltins = false;
6032 
6033  // If the declaration we're planning to build will be a function
6034  // or object with linkage, then look for another declaration with
6035  // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
6036  //
6037  // If the declaration we're planning to build will be declared with
6038  // external linkage in the translation unit, create any builtin with
6039  // the same name.
6041  /* Do nothing*/;
6042  else if (CurContext->isFunctionOrMethod() &&
6044  R->isFunctionType())) {
6045  IsLinkageLookup = true;
6046  CreateBuiltins =
6047  CurContext->getEnclosingNamespaceContext()->isTranslationUnit();
6048  } else if (CurContext->getRedeclContext()->isTranslationUnit() &&
6050  CreateBuiltins = true;
6051 
6052  if (IsLinkageLookup) {
6053  Previous.clear(LookupRedeclarationWithLinkage);
6054  Previous.setRedeclarationKind(ForExternalRedeclaration);
6055  }
6056 
6057  LookupName(Previous, S, CreateBuiltins);
6058  } else { // Something like "int foo::x;"
6059  LookupQualifiedName(Previous, DC);
6060 
6061  // C++ [dcl.meaning]p1:
6062  // When the declarator-id is qualified, the declaration shall refer to a
6063  // previously declared member of the class or namespace to which the
6064  // qualifier refers (or, in the case of a namespace, of an element of the
6065  // inline namespace set of that namespace (7.3.1)) or to a specialization
6066  // thereof; [...]
6067  //
6068  // Note that we already checked the context above, and that we do not have
6069  // enough information to make sure that Previous contains the declaration
6070  // we want to match. For example, given:
6071  //
6072  // class X {
6073  // void f();
6074  // void f(float);
6075  // };
6076  //
6077  // void X::f(int) { } // ill-formed
6078  //
6079  // In this case, Previous will point to the overload set
6080  // containing the two f's declared in X, but neither of them
6081  // matches.
6082 
6083  // C++ [dcl.meaning]p1:
6084  // [...] the member shall not merely have been introduced by a
6085  // using-declaration in the scope of the class or namespace nominated by
6086  // the nested-name-specifier of the declarator-id.
6088  }
6089 
6090  if (Previous.isSingleResult() &&
6091  Previous.getFoundDecl()->isTemplateParameter()) {
6092  // Maybe we will complain about the shadowed template parameter.
6093  if (!D.isInvalidType())
6094  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
6095  Previous.getFoundDecl());
6096 
6097  // Just pretend that we didn't see the previous declaration.
6098  Previous.clear();
6099  }
6100 
6101  if (!R->isFunctionType() && DiagnoseClassNameShadow(DC, NameInfo))
6102  // Forget that the previous declaration is the injected-class-name.
6103  Previous.clear();
6104 
6105  // In C++, the previous declaration we find might be a tag type
6106  // (class or enum). In this case, the new declaration will hide the
6107  // tag type. Note that this applies to functions, function templates, and
6108  // variables, but not to typedefs (C++ [dcl.typedef]p4) or variable templates.
6109  if (Previous.isSingleTagDecl() &&
6111  (TemplateParamLists.size() == 0 || R->isFunctionType()))
6112  Previous.clear();
6113 
6114  // Check that there are no default arguments other than in the parameters
6115  // of a function declaration (C++ only).
6116  if (getLangOpts().CPlusPlus)
6117  CheckExtraCXXDefaultArguments(D);
6118 
6119  NamedDecl *New;
6120 
6121  bool AddToScope = true;
6123  if (TemplateParamLists.size()) {
6124  Diag(D.getIdentifierLoc(), diag::err_template_typedef);
6125  return nullptr;
6126  }
6127 
6128  New = ActOnTypedefDeclarator(S, D, DC, TInfo, Previous);
6129  } else if (R->isFunctionType()) {
6130  New = ActOnFunctionDeclarator(S, D, DC, TInfo, Previous,
6131  TemplateParamLists,
6132  AddToScope);
6133  } else {
6134  New = ActOnVariableDeclarator(S, D, DC, TInfo, Previous, TemplateParamLists,
6135  AddToScope);
6136  }
6137 
6138  if (!New)
6139  return nullptr;
6140 
6141  // If this has an identifier and is not a function template specialization,
6142  // add it to the scope stack.
6143  if (New->getDeclName() && AddToScope)
6144  PushOnScopeChains(New, S);
6145 
6146  if (isInOpenMPDeclareTargetContext())
6147  checkDeclIsAllowedInOpenMPTarget(nullptr, New);
6148 
6149  return New;
6150 }
6151 
6152 /// Helper method to turn variable array types into constant array
6153 /// types in certain situations which would otherwise be errors (for
6154 /// GCC compatibility).
6156  ASTContext &Context,
6157  bool &SizeIsNegative,
6158  llvm::APSInt &Oversized) {
6159  // This method tries to turn a variable array into a constant
6160  // array even when the size isn't an ICE. This is necessary
6161  // for compatibility with code that depends on gcc's buggy
6162  // constant expression folding, like struct {char x[(int)(char*)2];}
6163  SizeIsNegative = false;
6164  Oversized = 0;
6165 
6166  if (T->isDependentType())
6167  return QualType();
6168 
6169  QualifierCollector Qs;
6170  const Type *Ty = Qs.strip(T);
6171 
6172  if (const PointerType* PTy = dyn_cast<PointerType>(Ty)) {
6173  QualType Pointee = PTy->getPointeeType();
6174  QualType FixedType =
6175  TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative,
6176  Oversized);
6177  if (FixedType.isNull()) return FixedType;
6178  FixedType = Context.getPointerType(FixedType);
6179  return Qs.apply(Context, FixedType);
6180  }
6181  if (const ParenType* PTy = dyn_cast<ParenType>(Ty)) {
6182  QualType Inner = PTy->getInnerType();
6183  QualType FixedType =
6184  TryToFixInvalidVariablyModifiedType(Inner, Context, SizeIsNegative,
6185  Oversized);
6186  if (FixedType.isNull()) return FixedType;
6187  FixedType = Context.getParenType(FixedType);
6188  return Qs.apply(Context, FixedType);
6189  }
6190 
6191  const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
6192  if (!VLATy)
6193  return QualType();
6194 
6195  QualType ElemTy = VLATy->getElementType();
6196  if (ElemTy->isVariablyModifiedType()) {
6197  ElemTy = TryToFixInvalidVariablyModifiedType(ElemTy, Context,
6198  SizeIsNegative, Oversized);
6199  if (ElemTy.isNull())
6200  return QualType();
6201  }
6202 
6203  Expr::EvalResult Result;
6204  if (!VLATy->getSizeExpr() ||
6205  !VLATy->getSizeExpr()->EvaluateAsInt(Result, Context))
6206  return QualType();
6207 
6208  llvm::APSInt Res = Result.Val.getInt();
6209 
6210  // Check whether the array size is negative.
6211  if (Res.isSigned() && Res.isNegative()) {
6212  SizeIsNegative = true;
6213  return QualType();
6214  }
6215 
6216  // Check whether the array is too large to be addressed.
6217  unsigned ActiveSizeBits =
6218  (!ElemTy->isDependentType() && !ElemTy->isVariablyModifiedType() &&
6219  !ElemTy->isIncompleteType() && !ElemTy->isUndeducedType())
6220  ? ConstantArrayType::getNumAddressingBits(Context, ElemTy, Res)
6221  : Res.getActiveBits();
6222  if (ActiveSizeBits > ConstantArrayType::getMaxSizeBits(Context)) {
6223  Oversized = Res;
6224  return QualType();
6225  }
6226 
6227  QualType FoldedArrayType = Context.getConstantArrayType(
6228  ElemTy, Res, VLATy->getSizeExpr(), ArrayType::Normal, 0);
6229  return Qs.apply(Context, FoldedArrayType);
6230 }
6231 
6232 static void
6234  SrcTL = SrcTL.getUnqualifiedLoc();
6235  DstTL = DstTL.getUnqualifiedLoc();
6236  if (PointerTypeLoc SrcPTL = SrcTL.getAs<PointerTypeLoc>()) {
6237  PointerTypeLoc DstPTL = DstTL.castAs<PointerTypeLoc>();
6238  FixInvalidVariablyModifiedTypeLoc(SrcPTL.getPointeeLoc(),
6239  DstPTL.getPointeeLoc());
6240  DstPTL.setStarLoc(SrcPTL.getStarLoc());
6241  return;
6242  }
6243  if (ParenTypeLoc SrcPTL = SrcTL.getAs<ParenTypeLoc>()) {
6244  ParenTypeLoc DstPTL = DstTL.castAs<ParenTypeLoc>();
6245  FixInvalidVariablyModifiedTypeLoc(SrcPTL.getInnerLoc(),
6246  DstPTL.getInnerLoc());
6247  DstPTL.setLParenLoc(SrcPTL.getLParenLoc());
6248  DstPTL.setRParenLoc(SrcPTL.getRParenLoc());
6249  return;
6250  }
6251  ArrayTypeLoc SrcATL = SrcTL.castAs<ArrayTypeLoc>();
6252  ArrayTypeLoc DstATL = DstTL.castAs<ArrayTypeLoc>();
6253  TypeLoc SrcElemTL = SrcATL.getElementLoc();
6254  TypeLoc DstElemTL = DstATL.getElementLoc();
6255  if (VariableArrayTypeLoc SrcElemATL =
6256  SrcElemTL.getAs<VariableArrayTypeLoc>()) {
6257  ConstantArrayTypeLoc DstElemATL = DstElemTL.castAs<ConstantArrayTypeLoc>();
6258  FixInvalidVariablyModifiedTypeLoc(SrcElemATL, DstElemATL);
6259  } else {
6260  DstElemTL.initializeFullCopy(SrcElemTL);
6261  }
6262  DstATL.setLBracketLoc(SrcATL.getLBracketLoc());
6263  DstATL.setSizeExpr(SrcATL.getSizeExpr());
6264  DstATL.setRBracketLoc(SrcATL.getRBracketLoc());
6265 }
6266 
6267 /// Helper method to turn variable array types into constant array
6268 /// types in certain situations which would otherwise be errors (for
6269 /// GCC compatibility).
6270 static TypeSourceInfo*
6272  ASTContext &Context,
6273  bool &SizeIsNegative,
6274  llvm::APSInt &Oversized) {
6275  QualType FixedTy
6276  = TryToFixInvalidVariablyModifiedType(TInfo->getType(), Context,
6277  SizeIsNegative, Oversized);
6278  if (FixedTy.isNull())
6279  return nullptr;
6280  TypeSourceInfo *FixedTInfo = Context.getTrivialTypeSourceInfo(FixedTy);
6282  FixedTInfo->getTypeLoc());
6283  return FixedTInfo;
6284 }
6285 
6286 /// Attempt to fold a variable-sized type to a constant-sized type, returning
6287 /// true if we were successful.
6289  QualType &T, SourceLocation Loc,
6290  unsigned FailedFoldDiagID) {
6291  bool SizeIsNegative;
6292  llvm::APSInt Oversized;
6294  TInfo, Context, SizeIsNegative, Oversized);
6295  if (FixedTInfo) {
6296  Diag(Loc, diag::ext_vla_folded_to_constant);
6297  TInfo = FixedTInfo;
6298  T = FixedTInfo->getType();
6299  return true;
6300  }
6301 
6302  if (SizeIsNegative)
6303  Diag(Loc, diag::err_typecheck_negative_array_size);
6304  else if (Oversized.getBoolValue())
6305  Diag(Loc, diag::err_array_too_large) << toString(Oversized, 10);
6306  else if (FailedFoldDiagID)
6307  Diag(Loc, FailedFoldDiagID);
6308  return false;
6309 }
6310 
6311 /// Register the given locally-scoped extern "C" declaration so
6312 /// that it can be found later for redeclarations. We include any extern "C"
6313 /// declaration that is not visible in the translation unit here, not just
6314 /// function-scope declarations.
6315 void
6317  if (!getLangOpts().CPlusPlus &&
6319  // Don't need to track declarations in the TU in C.
6320  return;
6321 
6322  // Note that we have a locally-scoped external with this name.
6324 }
6325 
6327  // FIXME: We can have multiple results via __attribute__((overloadable)).
6328  auto Result = Context.getExternCContextDecl()->lookup(Name);
6329  return Result.empty() ? nullptr : *Result.begin();
6330 }
6331 
6332 /// Diagnose function specifiers on a declaration of an identifier that
6333 /// does not identify a function.
6335  // FIXME: We should probably indicate the identifier in question to avoid
6336  // confusion for constructs like "virtual int a(), b;"
6337  if (DS.isVirtualSpecified())
6338  Diag(DS.getVirtualSpecLoc(),
6339  diag::err_virtual_non_function);
6340 
6341  if (DS.hasExplicitSpecifier())
6342  Diag(DS.getExplicitSpecLoc(),
6343  diag::err_explicit_non_function);
6344 
6345  if (DS.isNoreturnSpecified())
6346  Diag(DS.getNoreturnSpecLoc(),
6347  diag::err_noreturn_non_function);
6348 }
6349 
6350 NamedDecl*
6353  // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
6354  if (D.getCXXScopeSpec().isSet()) {
6355  Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
6356  << D.getCXXScopeSpec().getRange();
6357  D.setInvalidType();
6358  // Pretend we didn't see the scope specifier.
6359  DC = CurContext;
6360  Previous.clear();
6361  }
6362 
6363  DiagnoseFunctionSpecifiers(D.getDeclSpec());
6364 
6365  if (D.getDeclSpec().isInlineSpecified())
6366  Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
6367  << getLangOpts().CPlusPlus17;
6369  Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_invalid_constexpr)
6370  << 1 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
6371 
6375  diag::err_deduction_guide_invalid_specifier)
6376  << "typedef";
6377  else
6378  Diag(D.getName().StartLocation, diag::err_typedef_not_identifier)
6379  << D.getName().getSourceRange();
6380  return nullptr;
6381  }
6382 
6383  TypedefDecl *NewTD = ParseTypedefDecl(S, D, TInfo->getType(), TInfo);
6384  if (!NewTD) return nullptr;
6385 
6386  // Handle attributes prior to checking for duplicates in MergeVarDecl
6387  ProcessDeclAttributes(S, NewTD, D);
6388 
6389  CheckTypedefForVariablyModifiedType(S, NewTD);
6390 
6391  bool Redeclaration = D.isRedeclaration();
6392  NamedDecl *ND = ActOnTypedefNameDecl(S, DC, NewTD, Previous, Redeclaration);
6393  D.setRedeclaration(Redeclaration);
6394  return ND;
6395 }
6396 
6397 void
6399  // C99 6.7.7p2: If a typedef name specifies a variably modified type
6400  // then it shall have block scope.
6401  // Note that variably modified types must be fixed before merging the decl so
6402  // that redeclarations will match.
6403  TypeSourceInfo *TInfo = NewTD->getTypeSourceInfo();
6404  QualType T = TInfo->getType();
6405  if (T->isVariablyModifiedType()) {
6406  setFunctionHasBranchProtectedScope();
6407 
6408  if (S->getFnParent() == nullptr) {
6409  bool SizeIsNegative;
6410  llvm::APSInt Oversized;
6411  TypeSourceInfo *FixedTInfo =
6413  SizeIsNegative,
6414  Oversized);
6415  if (FixedTInfo) {
6416  Diag(NewTD->getLocation(), diag::ext_vla_folded_to_constant);
6417  NewTD->setTypeSourceInfo(FixedTInfo);
6418  } else {
6419  if (SizeIsNegative)
6420  Diag(NewTD->getLocation(), diag::err_typecheck_negative_array_size);
6421  else if (T->isVariableArrayType())
6422  Diag(NewTD->getLocation(), diag::err_vla_decl_in_file_scope);
6423  else if (Oversized.getBoolValue())
6424  Diag(NewTD->getLocation(), diag::err_array_too_large)
6425  << toString(Oversized, 10);
6426  else
6427  Diag(NewTD->getLocation(), diag::err_vm_decl_in_file_scope);
6428  NewTD->setInvalidDecl();
6429  }
6430  }
6431  }
6432 }
6433 
6434 /// ActOnTypedefNameDecl - Perform semantic checking for a declaration which
6435 /// declares a typedef-name, either using the 'typedef' type specifier or via
6436 /// a C++0x [dcl.typedef]p2 alias-declaration: 'using T = A;'.
6437 NamedDecl*
6439  LookupResult &Previous, bool &Redeclaration) {
6440 
6441  // Find the shadowed declaration before filtering for scope.
6442  NamedDecl *ShadowedDecl = getShadowedDeclaration(NewTD, Previous);
6443 
6444  // Merge the decl with the existing one if appropriate. If the decl is
6445  // in an outer scope, it isn't the same thing.
6446  FilterLookupForScope(Previous, DC, S, /*ConsiderLinkage*/false,
6447  /*AllowInlineNamespace*/false);
6449  if (!Previous.empty()) {
6450  Redeclaration = true;
6451  MergeTypedefNameDecl(S, NewTD, Previous);
6452  } else {
6453  inferGslPointerAttribute(NewTD);
6454  }
6455 
6456  if (ShadowedDecl && !Redeclaration)
6457  CheckShadow(NewTD, ShadowedDecl, Previous);
6458 
6459  // If this is the C FILE type, notify the AST context.
6460  if (IdentifierInfo *II = NewTD->getIdentifier())
6461  if (!NewTD->isInvalidDecl() &&
6463  if (II->isStr("FILE"))
6464  Context.setFILEDecl(NewTD);
6465  else if (II->isStr("jmp_buf"))
6466  Context.setjmp_bufDecl(NewTD);
6467  else if (II->isStr("sigjmp_buf"))
6468  Context.setsigjmp_bufDecl(NewTD);
6469  else if (II->isStr("ucontext_t"))
6470  Context.setucontext_tDecl(NewTD);
6471  }
6472 
6473  return NewTD;
6474 }
6475 
6476 /// Determines whether the given declaration is an out-of-scope
6477 /// previous declaration.
6478 ///
6479 /// This routine should be invoked when name lookup has found a
6480 /// previous declaration (PrevDecl) that is not in the scope where a
6481 /// new declaration by the same name is being introduced. If the new
6482 /// declaration occurs in a local scope, previous declarations with
6483 /// linkage may still be considered previous declarations (C99
6484 /// 6.2.2p4-5, C++ [basic.link]p6).
6485 ///
6486 /// \param PrevDecl the previous declaration found by name
6487 /// lookup
6488 ///
6489 /// \param DC the context in which the new declaration is being
6490 /// declared.
6491 ///
6492 /// \returns true if PrevDecl is an out-of-scope previous declaration
6493 /// for a new delcaration with the same name.
6494 static bool
6496  ASTContext &Context) {
6497  if (!PrevDecl)
6498  return false;
6499 
6500  if (!PrevDecl->hasLinkage())
6501  return false;
6502 
6503  if (Context.getLangOpts().CPlusPlus) {
6504  // C++ [basic.link]p6:
6505  // If there is a visible declaration of an entity with linkage
6506  // having the same name and type, ignoring entities declared
6507  // outside the innermost enclosing namespace scope, the block
6508  // scope declaration declares that same entity and receives the
6509  // linkage of the previous declaration.
6510  DeclContext *OuterContext = DC->getRedeclContext();
6511  if (!OuterContext->isFunctionOrMethod())
6512  // This rule only applies to block-scope declarations.
6513  return false;
6514 
6515  DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
6516  if (PrevOuterContext->isRecord())
6517  // We found a member function: ignore it.
6518  return false;
6519 
6520  // Find the innermost enclosing namespace for the new and
6521  // previous declarations.
6522  OuterContext = OuterContext->getEnclosingNamespaceContext();
6523  PrevOuterContext = PrevOuterContext->getEnclosingNamespaceContext();
6524 
6525  // The previous declaration is in a different namespace, so it
6526  // isn't the same function.
6527  if (!OuterContext->Equals(PrevOuterContext))
6528  return false;
6529  }
6530 
6531  return true;
6532 }
6533 
6535  CXXScopeSpec &SS = D.getCXXScopeSpec();
6536  if (!SS.isSet()) return;
6538 }
6539 
6541  QualType type = decl->getType();
6542  Qualifiers::ObjCLifetime lifetime = type.getObjCLifetime();
6543  if (lifetime == Qualifiers::OCL_Autoreleasing) {
6544  // Various kinds of declaration aren't allowed to be __autoreleasing.
6545  unsigned kind = -1U;
6546  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6547  if (var->hasAttr<BlocksAttr>())
6548  kind = 0; // __block
6549  else if (!var->hasLocalStorage())
6550  kind = 1; // global
6551  } else if (isa<ObjCIvarDecl>(decl)) {
6552  kind = 3; // ivar
6553  } else if (isa<FieldDecl>(decl)) {
6554  kind = 2; // field
6555  }
6556 
6557  if (kind != -1U) {
6558  Diag(decl->getLocation(), diag::err_arc_autoreleasing_var)
6559  << kind;
6560  }
6561  } else if (lifetime == Qualifiers::OCL_None) {
6562  // Try to infer lifetime.
6563  if (!type->isObjCLifetimeType())
6564  return false;
6565 
6566  lifetime = type->getObjCARCImplicitLifetime();
6567  type = Context.getLifetimeQualifiedType(type, lifetime);
6568  decl->setType(type);
6569  }
6570 
6571  if (VarDecl *var = dyn_cast<VarDecl>(decl)) {
6572  // Thread-local variables cannot have lifetime.
6573  if (lifetime && lifetime != Qualifiers::OCL_ExplicitNone &&
6574  var->getTLSKind()) {
6575  Diag(var->getLocation(), diag::err_arc_thread_ownership)
6576  << var->getType();
6577  return true;
6578  }
6579  }
6580 
6581  return false;
6582 }
6583 
6585  if (Decl->getType().hasAddressSpace())
6586  return;
6587  if (Decl->getType()->isDependentType())
6588  return;
6589  if (VarDecl *Var = dyn_cast<VarDecl>(Decl)) {
6590  QualType Type = Var->getType();
6591  if (Type->isSamplerT() || Type->isVoidType())
6592  return;
6593  LangAS ImplAS = LangAS::opencl_private;
6594  // OpenCL C v3.0 s6.7.8 - For OpenCL C 2.0 or with the
6595  // __opencl_c_program_scope_global_variables feature, the address space
6596  // for a variable at program scope or a static or extern variable inside
6597  // a function are inferred to be __global.
6598  if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()) &&
6599  Var->hasGlobalStorage())
6600  ImplAS = LangAS::opencl_global;
6601  // If the original type from a decayed type is an array type and that array
6602  // type has no address space yet, deduce it now.
6603  if (auto DT = dyn_cast<DecayedType>(Type)) {
6604  auto OrigTy = DT->getOriginalType();
6605  if (!OrigTy.hasAddressSpace() && OrigTy->isArrayType()) {
6606  // Add the address space to the original array type and then propagate
6607  // that to the element type through `getAsArrayType`.
6608  OrigTy = Context.getAddrSpaceQualType(OrigTy, ImplAS);
6609  OrigTy = QualType(Context.getAsArrayType(OrigTy), 0);
6610  // Re-generate the decayed type.
6611  Type = Context.getDecayedType(OrigTy);
6612  }
6613  }
6614  Type = Context.getAddrSpaceQualType(Type, ImplAS);
6615  // Apply any qualifiers (including address space) from the array type to
6616  // the element type. This implements C99 6.7.3p8: "If the specification of
6617  // an array type includes any type qualifiers, the element type is so
6618  // qualified, not the array type."
6619  if (Type->isArrayType())
6620  Type = QualType(Context.getAsArrayType(Type), 0);
6621  Decl->setType(Type);
6622  }
6623 }
6624 
6626  // Ensure that an auto decl is deduced otherwise the checks below might cache
6627  // the wrong linkage.
6628  assert(S.ParsingInitForAutoVars.count(&ND) == 0);
6629 
6630  // 'weak' only applies to declarations with external linkage.
6631  if (WeakAttr *Attr = ND.getAttr<WeakAttr>()) {
6632  if (!ND.isExternallyVisible()) {
6633  S.Diag(Attr->getLocation(), diag::err_attribute_weak_static);
6634  ND.dropAttr<WeakAttr>();
6635  }
6636  }
6637  if (WeakRefAttr *Attr = ND.getAttr<WeakRefAttr>()) {
6638  if (ND.isExternallyVisible()) {
6639  S.Diag(Attr->getLocation(), diag::err_attribute_weakref_not_static);
6640  ND.dropAttr<WeakRefAttr>();
6641  ND.dropAttr<AliasAttr>();
6642  }
6643  }
6644 
6645  if (auto *VD = dyn_cast<VarDecl>(&ND)) {
6646  if (VD->hasInit()) {
6647  if (const auto *Attr = VD->getAttr<AliasAttr>()) {
6648  assert(VD->isThisDeclarationADefinition() &&
6649  !VD->isExternallyVisible() && "Broken AliasAttr handled late!");
6650  S.Diag(Attr->getLocation(), diag::err_alias_is_definition) << VD << 0;
6651  VD->dropAttr<AliasAttr>();
6652  }
6653  }
6654  }
6655 
6656  // 'selectany' only applies to externally visible variable declarations.
6657  // It does not apply to functions.
6658  if (SelectAnyAttr *Attr = ND.getAttr<SelectAnyAttr>()) {
6659  if (isa<FunctionDecl>(ND) || !ND.isExternallyVisible()) {
6660  S.Diag(Attr->getLocation(),
6661  diag::err_attribute_selectany_non_extern_data);
6662  ND.dropAttr<SelectAnyAttr>();
6663  }
6664  }
6665 
6666  if (const InheritableAttr *Attr = getDLLAttr(&ND)) {
6667  auto *VD = dyn_cast<VarDecl>(&ND);
6668  bool IsAnonymousNS = false;
6669  bool IsMicrosoft = S.Context.getTargetInfo().getCXXABI().isMicrosoft();
6670  if (VD) {
6671  const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(VD->getDeclContext());
6672  while (NS && !IsAnonymousNS) {
6673  IsAnonymousNS = NS->isAnonymousNamespace();
6674  NS = dyn_cast<NamespaceDecl>(NS->getParent());
6675  }
6676  }
6677  // dll attributes require external linkage. Static locals may have external
6678  // linkage but still cannot be explicitly imported or exported.
6679  // In Microsoft mode, a variable defined in anonymous namespace must have
6680  // external linkage in order to be exported.
6681  bool AnonNSInMicrosoftMode = IsAnonymousNS && IsMicrosoft;
6682  if ((ND.isExternallyVisible() && AnonNSInMicrosoftMode) ||
6683  (!AnonNSInMicrosoftMode &&
6684  (!ND.isExternallyVisible() || (VD && VD->isStaticLocal())))) {
6685  S.Diag(ND.getLocation(), diag::err_attribute_dll_not_extern)
6686  << &ND << Attr;
6687  ND.setInvalidDecl();
6688  }
6689  }
6690 
6691  // Check the attributes on the function type, if any.
6692  if (const auto *FD = dyn_cast<FunctionDecl>(&ND)) {
6693  // Don't declare this variable in the second operand of the for-statement;
6694  // GCC miscompiles that by ending its lifetime before evaluating the
6695  // third operand. See gcc.gnu.org/PR86769.
6696  AttributedTypeLoc ATL;
6697  for (TypeLoc TL = FD->getTypeSourceInfo()->getTypeLoc();
6698  (ATL = TL.getAsAdjusted<AttributedTypeLoc>());
6699  TL = ATL.getModifiedLoc()) {
6700  // The [[lifetimebound]] attribute can be applied to the implicit object
6701  // parameter of a non-static member function (other than a ctor or dtor)
6702  // by applying it to the function type.
6703  if (const auto *A = ATL.getAttrAs<LifetimeBoundAttr>()) {
6704  const auto *MD = dyn_cast<CXXMethodDecl>(FD);
6705  if (!MD || MD->isStatic()) {
6706  S.Diag(A->getLocation(), diag::err_lifetimebound_no_object_param)
6707  << !MD << A->getRange();
6708  } else if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD)) {
6709  S.Diag(A->getLocation(), diag::err_lifetimebound_ctor_dtor)
6710  << isa<CXXDestructorDecl>(MD) << A->getRange();
6711  }
6712  }
6713  }
6714  }
6715 }
6716 
6718  NamedDecl *NewDecl,
6719  bool IsSpecialization,
6720  bool IsDefinition) {
6721  if (OldDecl->isInvalidDecl() || NewDecl->isInvalidDecl())
6722  return;
6723 
6724  bool IsTemplate = false;
6725  if (TemplateDecl *OldTD = dyn_cast<TemplateDecl>(OldDecl)) {
6726  OldDecl = OldTD->getTemplatedDecl();
6727  IsTemplate = true;
6728  if (!IsSpecialization)
6729  IsDefinition = false;
6730  }
6731  if (TemplateDecl *NewTD = dyn_cast<TemplateDecl>(NewDecl)) {
6732  NewDecl = NewTD->getTemplatedDecl();
6733  IsTemplate = true;
6734  }
6735 
6736  if (!OldDecl || !NewDecl)
6737  return;
6738 
6739  const DLLImportAttr *OldImportAttr = OldDecl->getAttr<DLLImportAttr>();
6740  const DLLExportAttr *OldExportAttr = OldDecl->getAttr<DLLExportAttr>();
6741  const DLLImportAttr *NewImportAttr = NewDecl->getAttr<DLLImportAttr>();
6742  const DLLExportAttr *NewExportAttr = NewDecl->getAttr<DLLExportAttr>();
6743 
6744  // dllimport and dllexport are inheritable attributes so we have to exclude
6745  // inherited attribute instances.
6746  bool HasNewAttr = (NewImportAttr && !NewImportAttr->isInherited()) ||
6747  (NewExportAttr && !NewExportAttr->isInherited());
6748 
6749  // A redeclaration is not allowed to add a dllimport or dllexport attribute,
6750  // the only exception being explicit specializations.
6751  // Implicitly generated declarations are also excluded for now because there
6752  // is no other way to switch these to use dllimport or dllexport.
6753  bool AddsAttr = !(OldImportAttr || OldExportAttr) && HasNewAttr;
6754 
6755  if (AddsAttr && !IsSpecialization && !OldDecl->isImplicit()) {
6756  // Allow with a warning for free functions and global variables.
6757  bool JustWarn = false;
6758  if (!OldDecl->isCXXClassMember()) {
6759  auto *VD = dyn_cast<VarDecl>(OldDecl);
6760  if (VD && !VD->getDescribedVarTemplate())
6761  JustWarn = true;
6762  auto *FD = dyn_cast<FunctionDecl>(OldDecl);
6763  if (FD && FD->getTemplatedKind() == FunctionDecl::TK_NonTemplate)
6764  JustWarn = true;
6765  }
6766 
6767  // We cannot change a declaration that's been used because IR has already
6768  // been emitted. Dllimported functions will still work though (modulo
6769  // address equality) as they can use the thunk.
6770  if (OldDecl->isUsed())
6771  if (!isa<FunctionDecl>(OldDecl) || !NewImportAttr)
6772  JustWarn = false;
6773 
6774  unsigned DiagID = JustWarn ? diag::warn_attribute_dll_redeclaration
6775  : diag::err_attribute_dll_redeclaration;
6776  S.Diag(NewDecl->getLocation(), DiagID)
6777  << NewDecl
6778  << (NewImportAttr ? (const Attr *)NewImportAttr : NewExportAttr);
6779  S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6780  if (!JustWarn) {
6781  NewDecl->setInvalidDecl();
6782  return;
6783  }
6784  }
6785 
6786  // A redeclaration is not allowed to drop a dllimport attribute, the only
6787  // exceptions being inline function definitions (except for function
6788  // templates), local extern declarations, qualified friend declarations or
6789  // special MSVC extension: in the last case, the declaration is treated as if
6790  // it were marked dllexport.
6791  bool IsInline = false, IsStaticDataMember = false, IsQualifiedFriend = false;
6792  bool IsMicrosoftABI = S.Context.getTargetInfo().shouldDLLImportComdatSymbols();
6793  if (const auto *VD = dyn_cast<VarDecl>(NewDecl)) {
6794  // Ignore static data because out-of-line definitions are diagnosed
6795  // separately.
6796  IsStaticDataMember = VD->isStaticDataMember();
6797  IsDefinition = VD->isThisDeclarationADefinition(S.Context) !=
6799  } else if (const auto *FD = dyn_cast<FunctionDecl>(NewDecl)) {
6800  IsInline = FD->isInlined();
6801  IsQualifiedFriend = FD->getQualifier() &&
6802  FD->getFriendObjectKind() == Decl::FOK_Declared;
6803  }
6804 
6805  if (OldImportAttr && !HasNewAttr &&
6806  (!IsInline || (IsMicrosoftABI && IsTemplate)) && !IsStaticDataMember &&
6807  !NewDecl->isLocalExternDecl() && !IsQualifiedFriend) {
6808  if (IsMicrosoftABI && IsDefinition) {
6809  S.Diag(NewDecl->getLocation(),
6810  diag::warn_redeclaration_without_import_attribute)
6811  << NewDecl;
6812  S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6813  NewDecl->dropAttr<DLLImportAttr>();
6814  NewDecl->addAttr(
6815  DLLExportAttr::CreateImplicit(S.Context, NewImportAttr->getRange()));
6816  } else {
6817  S.Diag(NewDecl->getLocation(),
6818  diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
6819  << NewDecl << OldImportAttr;
6820  S.Diag(OldDecl->getLocation(), diag::note_previous_declaration);
6821  S.Diag(OldImportAttr->getLocation(), diag::note_previous_attribute);
6822  OldDecl->dropAttr<DLLImportAttr>();
6823  NewDecl->dropAttr<DLLImportAttr>();
6824  }
6825  } else if (IsInline && OldImportAttr && !IsMicrosoftABI) {
6826  // In MinGW, seeing a function declared inline drops the dllimport
6827  // attribute.
6828  OldDecl->dropAttr<DLLImportAttr>();
6829  NewDecl->dropAttr<DLLImportAttr>();
6830  S.Diag(NewDecl->getLocation(),
6831  diag::warn_dllimport_dropped_from_inline_function)
6832  << NewDecl << OldImportAttr;
6833  }
6834 
6835  // A specialization of a class template member function is processed here
6836  // since it's a redeclaration. If the parent class is dllexport, the
6837  // specialization inherits that attribute. This doesn't happen automatically
6838  // since the parent class isn't instantiated until later.
6839  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDecl)) {
6840  if (MD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization &&
6841  !NewImportAttr && !NewExportAttr) {
6842  if (const DLLExportAttr *ParentExportAttr =
6843  MD->getParent()->getAttr<DLLExportAttr>()) {
6844  DLLExportAttr *NewAttr = ParentExportAttr->clone(S.Context);
6845  NewAttr->setInherited(true);
6846  NewDecl->addAttr(NewAttr);
6847  }
6848  }
6849  }
6850 }
6851 
6852 /// Given that we are within the definition of the given function,
6853 /// will that definition behave like C99's 'inline', where the
6854 /// definition is discarded except for optimization purposes?
6856  // Try to avoid calling GetGVALinkageForFunction.
6857 
6858  // All cases of this require the 'inline' keyword.
6859  if (!FD->isInlined()) return false;
6860 
6861  // This is only possible in C++ with the gnu_inline attribute.
6862  if (S.getLangOpts().CPlusPlus && !FD->hasAttr<GNUInlineAttr>())
6863  return false;
6864 
6865  // Okay, go ahead and call the relatively-more-expensive function.
6867 }
6868 
6869 /// Determine whether a variable is extern "C" prior to attaching
6870 /// an initializer. We can't just call isExternC() here, because that
6871 /// will also compute and cache whether the declaration is externally
6872 /// visible, which might change when we attach the initializer.
6873 ///
6874 /// This can only be used if the declaration is known to not be a
6875 /// redeclaration of an internal linkage declaration.
6876 ///
6877 /// For instance:
6878 ///
6879 /// auto x = []{};
6880 ///
6881 /// Attaching the initializer here makes this declaration not externally
6882 /// visible, because its type has internal linkage.
6883 ///
6884 /// FIXME: This is a hack.
6885 template<typename T>
6886 static bool isIncompleteDeclExternC(Sema &S, const T *D) {
6887  if (S.getLangOpts().CPlusPlus) {
6888  // In C++, the overloadable attribute negates the effects of extern "C".
6889  if (!D->isInExternCContext() || D->template hasAttr<OverloadableAttr>())
6890  return false;
6891 
6892  // So do CUDA's host/device attributes.
6893  if (S.getLangOpts().CUDA && (D->template hasAttr<CUDADeviceAttr>() ||
6894  D->template hasAttr<CUDAHostAttr>()))
6895  return false;
6896  }
6897  return D->isExternC();
6898 }
6899 
6900 static bool shouldConsiderLinkage(const VarDecl *VD) {
6901  const DeclContext *DC = VD->getDeclContext()->getRedeclContext();
6902  if (DC->isFunctionOrMethod() || isa<OMPDeclareReductionDecl>(DC) ||
6903  isa<OMPDeclareMapperDecl>(DC))
6904  return VD->hasExternalStorage();
6905  if (DC->isFileContext())
6906  return true;
6907  if (DC->isRecord())
6908  return false;
6909  if (isa<RequiresExprBodyDecl>(DC))
6910  return false;
6911  llvm_unreachable("Unexpected context");
6912 }
6913 
6914 static bool shouldConsiderLinkage(const FunctionDecl *FD) {
6915  const DeclContext *DC = FD->getDeclContext()->getRedeclContext();
6916  if (DC->isFileContext() || DC->isFunctionOrMethod() ||
6917  isa<OMPDeclareReductionDecl>(DC) || isa<OMPDeclareMapperDecl>(DC))
6918  return true;
6919  if (DC->isRecord())
6920  return false;
6921  llvm_unreachable("Unexpected context");
6922 }
6923 
6924 static bool hasParsedAttr(Scope *S, const Declarator &PD,
6926  // Check decl attributes on the DeclSpec.
6928  return true;
6929 
6930  // Walk the declarator structure, checking decl attributes that were in a type
6931  // position to the decl itself.
6932  for (unsigned I = 0, E = PD.getNumTypeObjects(); I != E; ++I) {
6933  if (PD.getTypeObject(I).getAttrs().hasAttribute(Kind))
6934  return true;
6935  }
6936 
6937  // Finally, check attributes on the decl itself.
6938  return PD.getAttributes().hasAttribute(Kind);
6939 }
6940 
6941 /// Adjust the \c DeclContext for a function or variable that might be a
6942 /// function-local external declaration.
6944  if (!DC->isFunctionOrMethod())
6945  return false;
6946 
6947  // If this is a local extern function or variable declared within a function
6948  // template, don't add it into the enclosing namespace scope until it is
6949  // instantiated; it might have a dependent type right now.
6950  if (DC->isDependentContext())
6951  return true;
6952 
6953  // C++11 [basic.link]p7:
6954  // When a block scope declaration of an entity with linkage is not found to
6955  // refer to some other declaration, then that entity is a member of the
6956  // innermost enclosing namespace.
6957  //
6958  // Per C++11 [namespace.def]p6, the innermost enclosing namespace is a
6959  // semantically-enclosing namespace, not a lexically-enclosing one.
6960  while (!DC->isFileContext() && !isa<LinkageSpecDecl>(DC))
6961  DC = DC->getParent();
6962  return true;
6963 }
6964 
6965 /// Returns true if given declaration has external C language linkage.
6966 static bool isDeclExternC(const Decl *D) {
6967  if (const auto *FD = dyn_cast<FunctionDecl>(D))
6968  return FD->isExternC();
6969  if (const auto *VD = dyn_cast<VarDecl>(D))
6970  return VD->isExternC();
6971 
6972  llvm_unreachable("Unknown type of decl!");
6973 }
6974 
6975 /// Returns true if there hasn't been any invalid type diagnosed.
6976 static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD) {
6977  DeclContext *DC = NewVD->getDeclContext();
6978  QualType R = NewVD->getType();
6979 
6980  // OpenCL v2.0 s6.9.b - Image type can only be used as a function argument.
6981  // OpenCL v2.0 s6.13.16.1 - Pipe type can only be used as a function
6982  // argument.
6983  if (!R->isSampledImageType() && (R->isImageType() || R->isPipeType())) {
6984  Se.Diag(NewVD->getLocation(),
6985  diag::err_opencl_type_can_only_be_used_as_function_parameter)
6986  << R;
6987  NewVD->setInvalidDecl();
6988  return false;
6989  }
6990 
6991  // OpenCL v1.2 s6.9.r:
6992  // The event type cannot be used to declare a program scope variable.
6993  // OpenCL v2.0 s6.9.q:
6994  // The clk_event_t and reserve_id_t types cannot be declared in program
6995  // scope.
6996  if (NewVD->hasGlobalStorage() && !NewVD->isStaticLocal()) {
6997  if (R->isReserveIDT() || R->isClkEventT() || R->isEventT()) {
6998  Se.Diag(NewVD->getLocation(),
6999  diag::err_invalid_type_for_program_scope_var)
7000  << R;
7001  NewVD->setInvalidDecl();
7002  return false;
7003  }
7004  }
7005 
7006  // OpenCL v1.0 s6.8.a.3: Pointers to functions are not allowed.
7007  if (!Se.getOpenCLOptions().isAvailableOption("__cl_clang_function_pointers",
7008  Se.getLangOpts())) {
7009  QualType NR = R.getCanonicalType();
7010  while (NR->isPointerType() || NR->isMemberFunctionPointerType() ||
7011  NR->isReferenceType()) {
7013  NR->isFunctionReferenceType()) {
7014  Se.Diag(NewVD->getLocation(), diag::err_opencl_function_pointer)
7015  << NR->isReferenceType();
7016  NewVD->setInvalidDecl();
7017  return false;
7018  }
7019  NR = NR->getPointeeType();
7020  }
7021  }
7022 
7023  if (!Se.getOpenCLOptions().isAvailableOption("cl_khr_fp16",
7024  Se.getLangOpts())) {
7025  // OpenCL v1.2 s6.1.1.1: reject declaring variables of the half and
7026  // half array type (unless the cl_khr_fp16 extension is enabled).
7027  if (Se.Context.getBaseElementType(R)->isHalfType()) {
7028  Se.Diag(NewVD->getLocation(), diag::err_opencl_half_declaration) << R;
7029  NewVD->setInvalidDecl();
7030  return false;
7031  }
7032  }
7033 
7034  // OpenCL v1.2 s6.9.r:
7035  // The event type cannot be used with the __local, __constant and __global
7036  // address space qualifiers.
7037  if (R->isEventT()) {
7039  Se.Diag(NewVD->getBeginLoc(), diag::err_event_t_addr_space_qual);
7040  NewVD->setInvalidDecl();
7041  return false;
7042  }
7043  }
7044 
7045  if (R->isSamplerT()) {
7046  // OpenCL v1.2 s6.9.b p4:
7047  // The sampler type cannot be used with the __local and __global address
7048  // space qualifiers.
7051  Se.Diag(NewVD->getLocation(), diag::err_wrong_sampler_addressspace);
7052  NewVD->setInvalidDecl();
7053  }
7054 
7055  // OpenCL v1.2 s6.12.14.1:
7056  // A global sampler must be declared with either the constant address
7057  // space qualifier or with the const qualifier.
7058  if (DC->isTranslationUnit() &&
7060  R.isConstQualified())) {
7061  Se.Diag(NewVD->getLocation(), diag::err_opencl_nonconst_global_sampler);
7062  NewVD->setInvalidDecl();
7063  }
7064  if (NewVD->isInvalidDecl())
7065  return false;
7066  }
7067 
7068  return true;
7069 }
7070 
7071 template <typename AttrTy>
7072 static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT) {
7073  const TypedefNameDecl *TND = TT->getDecl();
7074  if (const auto *Attribute = TND->getAttr<AttrTy>()) {
7075  AttrTy *Clone = Attribute->clone(S.Context);
7076  Clone->setInherited(true);
7077  D->addAttr(Clone);
7078  }
7079 }
7080 
7082  Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo,
7083  LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists,
7084  bool &AddToScope, ArrayRef<BindingDecl *> Bindings) {
7085  QualType R = TInfo->getType();
7086  DeclarationName Name = GetNameForDeclarator(D).getName();
7087 
7088  IdentifierInfo *II = Name.getAsIdentifierInfo();
7089 
7090  if (D.isDecompositionDeclarator()) {
7091  // Take the name of the first declarator as our name for diagnostic
7092  // purposes.
7093  auto &Decomp = D.getDecompositionDeclarator();
7094  if (!Decomp.bindings().empty()) {
7095  II = Decomp.bindings()[0].Name;
7096  Name = II;
7097  }
7098  } else if (!II) {
7099  Diag(D.getIdentifierLoc(), diag::err_bad_variable_name) << Name;
7100  return nullptr;
7101  }
7102 
7105 
7106  // dllimport globals without explicit storage class are treated as extern. We
7107  // have to change the storage class this early to get the right DeclContext.
7108  if (SC == SC_None && !DC->isRecord() &&
7109  hasParsedAttr(S, D, ParsedAttr::AT_DLLImport) &&
7110  !hasParsedAttr(S, D, ParsedAttr::AT_DLLExport))
7111  SC = SC_Extern;
7112 
7113  DeclContext *OriginalDC = DC;
7114  bool IsLocalExternDecl = SC == SC_Extern &&
7115  adjustContextForLocalExternDecl(DC);
7116 
7117  if (SCSpec == DeclSpec::SCS_mutable) {
7118  // mutable can only appear on non-static class members, so it's always
7119  // an error here
7120  Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
7121  D.setInvalidType();
7122  SC = SC_None;
7123  }
7124 
7125  if (getLangOpts().CPlusPlus11 && SCSpec == DeclSpec::SCS_register &&
7126  !D.getAsmLabel() && !getSourceManager().isInSystemMacro(
7128  // In C++11, the 'register' storage class specifier is deprecated.
7129  // Suppress the warning in system macros, it's used in macros in some
7130  // popular C system headers, such as in glibc's htonl() macro.
7132  getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
7133  : diag::warn_deprecated_register)
7135  }
7136 
7137  DiagnoseFunctionSpecifiers(D.getDeclSpec());
7138 
7139  if (!DC->isRecord() && S->getFnParent() == nullptr) {
7140  // C99 6.9p2: The storage-class specifiers auto and register shall not
7141  // appear in the declaration specifiers in an external declaration.
7142  // Global Register+Asm is a GNU extension we support.
7143  if (SC == SC_Auto || (SC == SC_Register && !D.getAsmLabel())) {
7144  Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
7145  D.setInvalidType();
7146  }
7147  }
7148 
7149  // If this variable has a VLA type and an initializer, try to
7150  // fold to a constant-sized type. This is otherwise invalid.
7151  if (D.hasInitializer() && R->isVariableArrayType())
7152  tryToFixVariablyModifiedVarType(TInfo, R, D.getIdentifierLoc(),
7153  /*DiagID=*/0);
7154 
7155  bool IsMemberSpecialization = false;
7156  bool IsVariableTemplateSpecialization = false;
7157  bool IsPartialSpecialization = false;
7158  bool IsVariableTemplate = false;
7159  VarDecl *NewVD = nullptr;
7160  VarTemplateDecl *NewTemplate = nullptr;
7161  TemplateParameterList *TemplateParams = nullptr;
7162  if (!getLangOpts().CPlusPlus) {
7163  NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(), D.getIdentifierLoc(),
7164  II, R, TInfo, SC);
7165 
7166  if (R->getContainedDeducedType())
7167  ParsingInitForAutoVars.insert(NewVD);
7168 
7169  if (D.isInvalidType())
7170  NewVD->setInvalidDecl();
7171 
7173  NewVD->hasLocalStorage())
7174  checkNonTrivialCUnion(NewVD->getType(), NewVD->getLocation(),
7175  NTCUC_AutoVar, NTCUK_Destruct);
7176  } else {
7177  bool Invalid = false;
7178 
7179  if (DC->isRecord() && !CurContext->isRecord()) {
7180  // This is an out-of-line definition of a static data member.
7181  switch (SC) {
7182  case SC_None:
7183  break;
7184  case SC_Static:
7186  diag::err_static_out_of_line)
7188  break;
7189  case SC_Auto:
7190  case SC_Register:
7191  case SC_Extern:
7192  // [dcl.stc] p2: The auto or register specifiers shall be applied only
7193  // to names of variables declared in a block or to function parameters.
7194  // [dcl.stc] p6: The extern specifier cannot be used in the declaration
7195  // of class members
7196 
7198  diag::err_storage_class_for_static_member)
7200  break;
7201  case SC_PrivateExtern:
7202  llvm_unreachable("C storage class in c++!");
7203  }
7204  }
7205 
7206  if (SC == SC_Static && CurContext->isRecord()) {
7207  if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
7208  // Walk up the enclosing DeclContexts to check for any that are
7209  // incompatible with static data members.
7210  const DeclContext *FunctionOrMethod = nullptr;
7211  const CXXRecordDecl *AnonStruct = nullptr;
7212  for (DeclContext *Ctxt = DC; Ctxt; Ctxt = Ctxt->getParent()) {
7213  if (Ctxt->isFunctionOrMethod()) {
7214  FunctionOrMethod = Ctxt;
7215  break;
7216  }
7217  const CXXRecordDecl *ParentDecl = dyn_cast<CXXRecordDecl>(Ctxt);
7218  if (ParentDecl && !ParentDecl->getDeclName()) {
7219  AnonStruct = ParentDecl;
7220  break;
7221  }
7222  }
7223  if (FunctionOrMethod) {
7224  // C++ [class.static.data]p5: A local class shall not have static data
7225  // members.
7226  Diag(D.getIdentifierLoc(),
7227  diag::err_static_data_member_not_allowed_in_local_class)
7228  << Name << RD->getDeclName() << RD->getTagKind();
7229  } else if (AnonStruct) {
7230  // C++ [class.static.data]p4: Unnamed classes and classes contained
7231  // directly or indirectly within unnamed classes shall not contain
7232  // static data members.
7233  Diag(D.getIdentifierLoc(),
7234  diag::err_static_data_member_not_allowed_in_anon_struct)
7235  << Name << AnonStruct->getTagKind();
7236  Invalid = true;
7237  } else if (RD->isUnion()) {
7238  // C++98 [class.union]p1: If a union contains a static data member,
7239  // the program is ill-formed. C++11 drops this restriction.
7240  Diag(D.getIdentifierLoc(),
7241  getLangOpts().CPlusPlus11
7242  ? diag::warn_cxx98_compat_static_data_member_in_union
7243  : diag::ext_static_data_member_in_union) << Name;
7244  }
7245  }
7246  }
7247 
7248  // Match up the template parameter lists with the scope specifier, then
7249  // determine whether we have a template or a template specialization.
7250  bool InvalidScope = false;
7251  TemplateParams = MatchTemplateParametersToScopeSpecifier(
7253  D.getCXXScopeSpec(),
7255  ? D.getName().TemplateId
7256  : nullptr,
7257  TemplateParamLists,
7258  /*never a friend*/ false, IsMemberSpecialization, InvalidScope);
7259  Invalid |= InvalidScope;
7260 
7261  if (TemplateParams) {
7262  if (!TemplateParams->size() &&
7264  // There is an extraneous 'template<>' for this variable. Complain
7265  // about it, but allow the declaration of the variable.
7266  Diag(TemplateParams->getTemplateLoc(),
7267  diag::err_template_variable_noparams)
7268  << II
7269  << SourceRange(TemplateParams->getTemplateLoc(),
7270  TemplateParams->getRAngleLoc());
7271  TemplateParams = nullptr;
7272  } else {
7273  // Check that we can declare a template here.
7274  if (CheckTemplateDeclScope(S, TemplateParams))
7275  return nullptr;
7276 
7278  // This is an explicit specialization or a partial specialization.
7279  IsVariableTemplateSpecialization = true;
7280  IsPartialSpecialization = TemplateParams->size() > 0;
7281  } else { // if (TemplateParams->size() > 0)
7282  // This is a template declaration.
7283  IsVariableTemplate = true;
7284 
7285  // Only C++1y supports variable templates (N3651).
7286  Diag(D.getIdentifierLoc(),
7287  getLangOpts().CPlusPlus14
7288  ? diag::warn_cxx11_compat_variable_template
7289  : diag::ext_variable_template);
7290  }
7291  }
7292  } else {
7293  // Check that we can declare a member specialization here.
7294  if (!TemplateParamLists.empty() && IsMemberSpecialization &&
7295  CheckTemplateDeclScope(S, TemplateParamLists.back()))
7296  return nullptr;
7297  assert((Invalid ||
7299  "should have a 'template<>' for this decl");
7300  }
7301 
7302  if (IsVariableTemplateSpecialization) {
7303  SourceLocation TemplateKWLoc =
7304  TemplateParamLists.size() > 0
7305  ? TemplateParamLists[0]->getTemplateLoc()
7306  : SourceLocation();
7307  DeclResult Res = ActOnVarTemplateSpecialization(
7308  S, D, TInfo, TemplateKWLoc, TemplateParams, SC,
7310  if (Res.isInvalid())
7311  return nullptr;
7312  NewVD = cast<VarDecl>(Res.get());
7313  AddToScope = false;
7314  } else if (D.isDecompositionDeclarator()) {
7315  NewVD = DecompositionDecl::Create(Context, DC, D.getBeginLoc(),
7316  D.getIdentifierLoc(), R, TInfo, SC,
7317  Bindings);
7318  } else
7319  NewVD = VarDecl::Create(Context, DC, D.getBeginLoc(),
7320  D.getIdentifierLoc(), II, R, TInfo, SC);
7321 
7322  // If this is supposed to be a variable template, create it as such.
7323  if (IsVariableTemplate) {
7324  NewTemplate =
7325  VarTemplateDecl::Create(Context, DC, D.getIdentifierLoc(), Name,
7326  TemplateParams, NewVD);
7327  NewVD->setDescribedVarTemplate(NewTemplate);
7328  }
7329 
7330  // If this decl has an auto type in need of deduction, make a note of the
7331  // Decl so we can diagnose uses of it in its own initializer.
7332  if (R->getContainedDeducedType())
7333  ParsingInitForAutoVars.insert(NewVD);
7334 
7335  if (D.isInvalidType() || Invalid) {
7336  NewVD->setInvalidDecl();
7337  if (NewTemplate)
7338  NewTemplate->setInvalidDecl();
7339  }
7340 
7341  SetNestedNameSpecifier(*this, NewVD, D);
7342 
7343  // If we have any template parameter lists that don't directly belong to
7344  // the variable (matching the scope specifier), store them.
7345  unsigned VDTemplateParamLists = TemplateParams ? 1 : 0;
7346  if (TemplateParamLists.size() > VDTemplateParamLists)
7348  Context, TemplateParamLists.drop_back(VDTemplateParamLists));
7349  }
7350 
7351  if (D.getDeclSpec().isInlineSpecified()) {
7352  if (!getLangOpts().CPlusPlus) {
7353  Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
7354  << 0;
7355  } else if (CurContext->isFunctionOrMethod()) {
7356  // 'inline' is not allowed on block scope variable declaration.
7358  diag::err_inline_declaration_block_scope) << Name
7360  } else {
7362  getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_inline_variable
7363  : diag::ext_inline_variable);
7364  NewVD->setInlineSpecified();
7365  }
7366  }
7367 
7368  // Set the lexical context. If the declarator has a C++ scope specifier, the
7369  // lexical context will be different from the semantic context.
7370  NewVD->setLexicalDeclContext(CurContext);
7371  if (NewTemplate)
7372  NewTemplate->setLexicalDeclContext(CurContext);
7373 
7374  if (IsLocalExternDecl) {
7375  if (D.isDecompositionDeclarator())
7376  for (auto *B : Bindings)
7377  B->setLocalExternDecl();
7378  else
7379  NewVD->setLocalExternDecl();
7380  }
7381 
7382  bool EmitTLSUnsupportedError = false;
7384  // C++11 [dcl.stc]p4:
7385  // When thread_local is applied to a variable of block scope the
7386  // storage-class-specifier static is implied if it does not appear
7387  // explicitly.
7388  // Core issue: 'static' is not implied if the variable is declared
7389  // 'extern'.
7390  if (NewVD->hasLocalStorage() &&
7391  (SCSpec != DeclSpec::SCS_unspecified ||
7392  TSCS != DeclSpec::TSCS_thread_local ||
7393  !DC->isFunctionOrMethod()))
7395  diag::err_thread_non_global)
7396  << DeclSpec::getSpecifierName(TSCS);
7397  else if (!Context.getTargetInfo().isTLSSupported()) {
7398  if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7399  getLangOpts().SYCLIsDevice) {
7400  // Postpone error emission until we've collected attributes required to
7401  // figure out whether it's a host or device variable and whether the
7402  // error should be ignored.
7403  EmitTLSUnsupportedError = true;
7404  // We still need to mark the variable as TLS so it shows up in AST with
7405  // proper storage class for other tools to use even if we're not going
7406  // to emit any code for it.
7407  NewVD->setTSCSpec(TSCS);
7408  } else
7410  diag::err_thread_unsupported);
7411  } else
7412  NewVD->setTSCSpec(TSCS);
7413  }
7414 
7415  // Global variables with types decorated with device_global attribute must be
7416  // static if they are declared in SYCL device code.
7417  if (getLangOpts().SYCLIsDevice) {
7418  if (SCSpec != DeclSpec::SCS_static && !NewVD->hasGlobalStorage() &&
7419  isTypeDecoratedWithDeclAttribute<SYCLDeviceGlobalAttr>(
7420  NewVD->getType()))
7421  Diag(D.getIdentifierLoc(), diag::err_sycl_device_global_incorrect_scope);
7422 
7423  // Static variables declared inside SYCL device code must be const or
7424  // constexpr unless their types are decorated with global_variable_allowed
7425  // attribute.
7426  if (SCSpec == DeclSpec::SCS_static && !R.isConstant(Context) &&
7427  !isTypeDecoratedWithDeclAttribute<SYCLGlobalVariableAllowedAttr>(
7428  NewVD->getType()))
7429  SYCLDiagIfDeviceCode(D.getIdentifierLoc(), diag::err_sycl_restrict)
7431  }
7432 
7433  switch (D.getDeclSpec().getConstexprSpecifier()) {
7435  break;
7436 
7439  diag::err_constexpr_wrong_decl_kind)
7440  << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
7441  LLVM_FALLTHROUGH;
7442 
7444  NewVD->setConstexpr(true);
7445  // C++1z [dcl.spec.constexpr]p1:
7446  // A static data member declared with the constexpr specifier is
7447  // implicitly an inline variable.
7448  if (NewVD->isStaticDataMember() &&
7449  (getLangOpts().CPlusPlus17 ||
7450  Context.getTargetInfo().getCXXABI().isMicrosoft()))
7451  NewVD->setImplicitlyInline();
7452  break;
7453 
7455  if (!NewVD->hasGlobalStorage())
7457  diag::err_constinit_local_variable);
7458  else
7459  NewVD->addAttr(ConstInitAttr::Create(
7460  Context, D.getDeclSpec().getConstexprSpecLoc(),
7461  AttributeCommonInfo::AS_Keyword, ConstInitAttr::Keyword_constinit));
7462  break;
7463  }
7464 
7465  // C99 6.7.4p3
7466  // An inline definition of a function with external linkage shall
7467  // not contain a definition of a modifiable object with static or
7468  // thread storage duration...
7469  // We only apply this when the function is required to be defined
7470  // elsewhere, i.e. when the function is not 'extern inline'. Note
7471  // that a local variable with thread storage duration still has to
7472  // be marked 'static'. Also note that it's possible to get these
7473  // semantics in C++ using __attribute__((gnu_inline)).
7474  if (SC == SC_Static && S->getFnParent() != nullptr &&
7475  !NewVD->getType().isConstQualified()) {
7476  FunctionDecl *CurFD = getCurFunctionDecl();
7477  if (CurFD && isFunctionDefinitionDiscarded(*this, CurFD)) {
7479  diag::warn_static_local_in_extern_inline);
7480  MaybeSuggestAddingStaticToDecl(CurFD);
7481  }
7482  }
7483 
7485  if (IsVariableTemplateSpecialization)
7486  Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7487  << (IsPartialSpecialization ? 1 : 0)
7490  else if (IsMemberSpecialization)
7491  Diag(NewVD->getLocation(), diag::err_module_private_specialization)
7492  << 2
7494  else if (NewVD->hasLocalStorage())
7495  Diag(NewVD->getLocation(), diag::err_module_private_local)
7496  << 0 << NewVD
7500  else {
7501  NewVD->setModulePrivate();
7502  if (NewTemplate)
7503  NewTemplate->setModulePrivate();
7504  for (auto *B : Bindings)
7505  B->setModulePrivate();
7506  }
7507  }
7508 
7509  if (getLangOpts().OpenCL) {
7510  deduceOpenCLAddressSpace(NewVD);
7511 
7513  if (TSC != TSCS_unspecified) {
7515  diag::err_opencl_unknown_type_specifier)
7516  << getLangOpts().getOpenCLVersionString()
7517  << DeclSpec::getSpecifierName(TSC) << 1;
7518  NewVD->setInvalidDecl();
7519  }
7520  }
7521 
7522  // Handle attributes prior to checking for duplicates in MergeVarDecl
7523  ProcessDeclAttributes(S, NewVD, D);
7524 
7525  // FIXME: This is probably the wrong location to be doing this and we should
7526  // probably be doing this for more attributes (especially for function
7527  // pointer attributes such as format, warn_unused_result, etc.). Ideally
7528  // the code to copy attributes would be generated by TableGen.
7529  if (R->isFunctionPointerType())
7530  if (const auto *TT = R->getAs<TypedefType>())
7531  copyAttrFromTypedefToDecl<AllocSizeAttr>(*this, NewVD, TT);
7532 
7533  if (getLangOpts().CUDA || getLangOpts().OpenMPIsDevice ||
7534  getLangOpts().SYCLIsDevice) {
7535  if (EmitTLSUnsupportedError &&
7536  ((getLangOpts().CUDA && DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) ||
7537  (getLangOpts().OpenMPIsDevice &&
7538  OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(NewVD))))
7540  diag::err_thread_unsupported);
7541 
7542  if (EmitTLSUnsupportedError &&
7543  (LangOpts.SYCLIsDevice || (LangOpts.OpenMP && LangOpts.OpenMPIsDevice)))
7544  targetDiag(D.getIdentifierLoc(), diag::err_thread_unsupported);
7545  // CUDA B.2.5: "__shared__ and __constant__ variables have implied static
7546  // storage [duration]."
7547  if (SC == SC_None && S->getFnParent() != nullptr &&
7548  (NewVD->hasAttr<CUDASharedAttr>() ||
7549  NewVD->hasAttr<CUDAConstantAttr>())) {
7550  NewVD->setStorageClass(SC_Static);
7551  }
7552  }
7553 
7554  // Ensure that dllimport globals without explicit storage class are treated as
7555  // extern. The storage class is set above using parsed attributes. Now we can
7556  // check the VarDecl itself.
7557  assert(!NewVD->hasAttr<DLLImportAttr>() ||
7558  NewVD->getAttr<DLLImportAttr>()->isInherited() ||
7559  NewVD->isStaticDataMember() || NewVD->getStorageClass() != SC_None);
7560 
7561  // In auto-retain/release, infer strong retension for variables of
7562  // retainable type.
7563  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewVD))
7564  NewVD->setInvalidDecl();
7565 
7566  // Handle GNU asm-label extension (encoded as an attribute).
7567  if (Expr *E = (Expr*)D.getAsmLabel()) {
7568  // The parser guarantees this is a string.
7569  StringLiteral *SE = cast<StringLiteral>(E);
7570  StringRef Label = SE->getString();
7571  if (S->getFnParent() != nullptr) {
7572  switch (SC) {
7573  case SC_None:
7574  case SC_Auto:
7575  Diag(E->getExprLoc(), diag::warn_asm_label_on_auto_decl) << Label;
7576  break;
7577  case SC_Register:
7578  // Local Named register
7579  if (!Context.getTargetInfo().isValidGCCRegisterName(Label) &&
7580  DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl()))
7581  Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7582  break;
7583  case SC_Static:
7584  case SC_Extern:
7585  case SC_PrivateExtern:
7586  break;
7587  }
7588  } else if (SC == SC_Register) {
7589  // Global Named register
7590  if (DeclAttrsMatchCUDAMode(getLangOpts(), NewVD)) {
7591  const auto &TI = Context.getTargetInfo();
7592  bool HasSizeMismatch;
7593 
7594  if (!TI.isValidGCCRegisterName(Label))
7595  Diag(E->getExprLoc(), diag::err_asm_unknown_register_name) << Label;
7596  else if (!TI.validateGlobalRegisterVariable(Label,
7597  Context.getTypeSize(R),
7598  HasSizeMismatch))
7599  Diag(E->getExprLoc(), diag::err_asm_invalid_global_var_reg) << Label;
7600  else if (HasSizeMismatch)
7601  Diag(E->getExprLoc(), diag::err_asm_register_size_mismatch) << Label;
7602  }
7603 
7604  if (!R->isIntegralType(Context) && !R->isPointerType()) {
7605  Diag(D.getBeginLoc(), diag::err_asm_bad_register_type);
7606  NewVD->setInvalidDecl(true);
7607  }
7608  }
7609 
7610  NewVD->addAttr(AsmLabelAttr::Create(Context, Label,
7611  /*IsLiteralLabel=*/true,
7612  SE->getStrTokenLoc(0)));
7613  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
7614  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
7615  ExtnameUndeclaredIdentifiers.find(NewVD->getIdentifier());
7616  if (I != ExtnameUndeclaredIdentifiers.end()) {
7617  if (isDeclExternC(NewVD)) {
7618  NewVD->addAttr(I->second);
7619  ExtnameUndeclaredIdentifiers.erase(I);
7620  } else
7621  Diag(NewVD->getLocation(), diag::warn_redefine_extname_not_applied)
7622  << /*Variable*/1 << NewVD;
7623  }
7624  }
7625 
7626  // Find the shadowed declaration before filtering for scope.
7627  NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
7628  ? getShadowedDeclaration(NewVD, Previous)
7629  : nullptr;
7630 
7631  // Don't consider existing declarations that are in a different
7632  // scope and are out-of-semantic-context declarations (if the new
7633  // declaration has linkage).
7634  FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewVD),
7635  D.getCXXScopeSpec().isNotEmpty() ||
7636  IsMemberSpecialization ||
7637  IsVariableTemplateSpecialization);
7638 
7639  // Check whether the previous declaration is in the same block scope. This
7640  // affects whether we merge types with it, per C++11 [dcl.array]p3.
7641  if (getLangOpts().CPlusPlus &&
7642  NewVD->isLocalVarDecl() && NewVD->hasExternalStorage())
7644  Previous.isSingleResult() && !Previous.isShadowed() &&
7645  isDeclInScope(Previous.getFoundDecl(), OriginalDC, S, false));
7646 
7647  if (!getLangOpts().CPlusPlus) {
7648  D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7649  } else {
7650  // If this is an explicit specialization of a static data member, check it.
7651  if (IsMemberSpecialization && !NewVD->isInvalidDecl() &&
7652  CheckMemberSpecialization(NewVD, Previous))
7653  NewVD->setInvalidDecl();
7654 
7655  // Merge the decl with the existing one if appropriate.
7656  if (!Previous.empty()) {
7657  if (Previous.isSingleResult() &&
7658  isa<FieldDecl>(Previous.getFoundDecl()) &&
7659  D.getCXXScopeSpec().isSet()) {
7660  // The user tried to define a non-static data member
7661  // out-of-line (C++ [dcl.meaning]p1).
7662  Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
7663  << D.getCXXScopeSpec().getRange();
7664  Previous.clear();
7665  NewVD->setInvalidDecl();
7666  }
7667  } else if (D.getCXXScopeSpec().isSet()) {
7668  // No previous declaration in the qualifying scope.
7669  Diag(D.getIdentifierLoc(), diag::err_no_member)
7670  << Name << computeDeclContext(D.getCXXScopeSpec(), true)
7671  << D.getCXXScopeSpec().getRange();
7672  NewVD->setInvalidDecl();
7673  }
7674 
7675  if (!IsVariableTemplateSpecialization)
7676  D.setRedeclaration(CheckVariableDeclaration(NewVD, Previous));
7677 
7678  if (NewTemplate) {
7679  VarTemplateDecl *PrevVarTemplate =
7680  NewVD->getPreviousDecl()
7682  : nullptr;
7683 
7684  // Check the template parameter list of this declaration, possibly
7685  // merging in the template parameter list from the previous variable
7686  // template declaration.
7687  if (CheckTemplateParameterList(
7688  TemplateParams,
7689  PrevVarTemplate ? PrevVarTemplate->getTemplateParameters()
7690  : nullptr,
7691  (D.getCXXScopeSpec().isSet() && DC && DC->isRecord() &&
7692  DC->isDependentContext())
7693  ? TPC_ClassTemplateMember
7694  : TPC_VarTemplate))
7695  NewVD->setInvalidDecl();
7696 
7697  // If we are providing an explicit specialization of a static variable
7698  // template, make a note of that.
7699  if (PrevVarTemplate &&
7700  PrevVarTemplate->getInstantiatedFromMemberTemplate())
7701  PrevVarTemplate->setMemberSpecialization();
7702  }
7703  }
7704 
7705  // Diagnose shadowed variables iff this isn't a redeclaration.
7706  if (ShadowedDecl && !D.isRedeclaration())
7707  CheckShadow(NewVD, ShadowedDecl, Previous);
7708 
7709  ProcessPragmaWeak(S, NewVD);
7710 
7711  // If this is the first declaration of an extern C variable, update
7712  // the map of such variables.
7713  if (NewVD->isFirstDecl() && !NewVD->isInvalidDecl() &&
7714  isIncompleteDeclExternC(*this, NewVD))
7715  RegisterLocallyScopedExternCDecl(NewVD, S);
7716 
7717  if (getLangOpts().CPlusPlus && NewVD->isStaticLocal()) {
7718  MangleNumberingContext *MCtx;
7719  Decl *ManglingContextDecl;
7720  std::tie(MCtx, ManglingContextDecl) =
7721  getCurrentMangleNumberContext(NewVD->getDeclContext());
7722  if (MCtx) {
7723  Context.setManglingNumber(
7724  NewVD, MCtx->getManglingNumber(
7725  NewVD, getMSManglingNumber(getLangOpts(), S)));
7726  Context.setStaticLocalNumber(NewVD, MCtx->getStaticLocalNumber(NewVD));
7727  }
7728  }
7729 
7730  // Special handling of variable named 'main'.
7731  if (Name.getAsIdentifierInfo() && Name.getAsIdentifierInfo()->isStr("main") &&
7733  !getLangOpts().Freestanding && !NewVD->getDescribedVarTemplate()) {
7734 
7735  // C++ [basic.start.main]p3
7736  // A program that declares a variable main at global scope is ill-formed.
7737  if (getLangOpts().CPlusPlus)
7738  Diag(D.getBeginLoc(), diag::err_main_global_variable);
7739 
7740  // In C, and external-linkage variable named main results in undefined
7741  // behavior.
7742  else if (NewVD->hasExternalFormalLinkage())
7743  Diag(D.getBeginLoc(), diag::warn_main_redefined);
7744  }
7745 
7746  if (D.isRedeclaration() && !Previous.empty()) {
7747  NamedDecl *Prev = Previous.getRepresentativeDecl();
7748  checkDLLAttributeRedeclaration(*this, Prev, NewVD, IsMemberSpecialization,
7749  D.isFunctionDefinition());
7750  }
7751 
7752  if (NewTemplate) {
7753  if (NewVD->isInvalidDecl())
7754  NewTemplate->setInvalidDecl();
7755  ActOnDocumentableDecl(NewTemplate);
7756  return NewTemplate;
7757  }
7758 
7759  if (IsMemberSpecialization && !NewVD->isInvalidDecl())
7760  CompleteMemberSpecialization(NewVD, Previous);
7761 
7762  addSyclVarDecl(NewVD);
7763  return NewVD;
7764 }
7765 
7766 /// Enum describing the %select options in diag::warn_decl_shadow.
7775 };
7776 
7777 /// Determine what kind of declaration we're shadowing.
7779  const DeclContext *OldDC) {
7780  if (isa<TypeAliasDecl>(ShadowedDecl))
7781  return SDK_Using;
7782  else if (isa<TypedefDecl>(ShadowedDecl))
7783  return SDK_Typedef;
7784  else if (isa<BindingDecl>(ShadowedDecl))
7785  return SDK_StructuredBinding;
7786  else if (isa<RecordDecl>(OldDC))
7787  return isa<FieldDecl>(ShadowedDecl) ? SDK_Field : SDK_StaticMember;
7788 
7789  return OldDC->isFileContext() ? SDK_Global : SDK_Local;
7790 }
7791 
7792 /// Return the location of the capture if the given lambda captures the given
7793 /// variable \p VD, or an invalid source location otherwise.
7795  const VarDecl *VD) {
7796  for (const Capture &Capture : LSI->Captures) {
7797  if (Capture.isVariableCapture() && Capture.getVariable() == VD)
7798  return Capture.getLocation();
7799  }
7800  return SourceLocation();
7801 }
7802 
7804  const LookupResult &R) {
7805  // Only diagnose if we're shadowing an unambiguous field or variable.
7807  return false;
7808 
7809  // Return false if warning is ignored.
7810  return !Diags.isIgnored(diag::warn_decl_shadow, R.getNameLoc());
7811 }
7812 
7813 /// Return the declaration shadowed by the given variable \p D, or null
7814 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7816  const LookupResult &R) {
7817  if (!shouldWarnIfShadowedDecl(Diags, R))
7818  return nullptr;
7819 
7820  // Don't diagnose declarations at file scope.
7821  if (D->hasGlobalStorage())
7822  return nullptr;
7823 
7824  NamedDecl *ShadowedDecl = R.getFoundDecl();
7825  return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7826  : nullptr;
7827 }
7828 
7829 /// Return the declaration shadowed by the given typedef \p D, or null
7830 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7832  const LookupResult &R) {
7833  // Don't warn if typedef declaration is part of a class
7834  if (D->getDeclContext()->isRecord())
7835  return nullptr;
7836 
7837  if (!shouldWarnIfShadowedDecl(Diags, R))
7838  return nullptr;
7839 
7840  NamedDecl *ShadowedDecl = R.getFoundDecl();
7841  return isa<TypedefNameDecl>(ShadowedDecl) ? ShadowedDecl : nullptr;
7842 }
7843 
7844 /// Return the declaration shadowed by the given variable \p D, or null
7845 /// if it doesn't shadow any declaration or shadowing warnings are disabled.
7847  const LookupResult &R) {
7848  if (!shouldWarnIfShadowedDecl(Diags, R))
7849  return nullptr;
7850 
7851  NamedDecl *ShadowedDecl = R.getFoundDecl();
7852  return isa<VarDecl, FieldDecl, BindingDecl>(ShadowedDecl) ? ShadowedDecl
7853  : nullptr;
7854 }
7855 
7856 /// Diagnose variable or built-in function shadowing. Implements
7857 /// -Wshadow.
7858 ///
7859 /// This method is called whenever a VarDecl is added to a "useful"
7860 /// scope.
7861 ///
7862 /// \param ShadowedDecl the declaration that is shadowed by the given variable
7863 /// \param R the lookup of the name
7864 ///
7865 void Sema::CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl,
7866  const LookupResult &R) {
7867  DeclContext *NewDC = D->getDeclContext();
7868 
7869  if (FieldDecl *FD = dyn_cast<FieldDecl>(ShadowedDecl)) {
7870  // Fields are not shadowed by variables in C++ static methods.
7871  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewDC))
7872  if (MD->isStatic())
7873  return;
7874 
7875  // Fields shadowed by constructor parameters are a special case. Usually
7876  // the constructor initializes the field with the parameter.
7877  if (isa<CXXConstructorDecl>(NewDC))
7878  if (const auto PVD = dyn_cast<ParmVarDecl>(D)) {
7879  // Remember that this was shadowed so we can either warn about its
7880  // modification or its existence depending on warning settings.
7881  ShadowingDecls.insert({PVD->getCanonicalDecl(), FD});
7882  return;
7883  }
7884  }
7885 
7886  if (VarDecl *shadowedVar = dyn_cast<VarDecl>(ShadowedDecl))
7887  if (shadowedVar->isExternC()) {
7888  // For shadowing external vars, make sure that we point to the global
7889  // declaration, not a locally scoped extern declaration.
7890  for (auto I : shadowedVar->redecls())
7891  if (I->isFileVarDecl()) {
7892  ShadowedDecl = I;
7893  break;
7894  }
7895  }
7896 
7897  DeclContext *OldDC = ShadowedDecl->getDeclContext()->getRedeclContext();
7898 
7899  unsigned WarningDiag = diag::warn_decl_shadow;
7900  SourceLocation CaptureLoc;
7901  if (isa<VarDecl>(D) && isa<VarDecl>(ShadowedDecl) && NewDC &&
7902  isa<CXXMethodDecl>(NewDC)) {
7903  if (const auto *RD = dyn_cast<CXXRecordDecl>(NewDC->getParent())) {
7904  if (RD->isLambda() && OldDC->Encloses(NewDC->getLexicalParent())) {
7905  if (RD->getLambdaCaptureDefault() == LCD_None) {
7906  // Try to avoid warnings for lambdas with an explicit capture list.
7907  const auto *LSI = cast<LambdaScopeInfo>(getCurFunction());
7908  // Warn only when the lambda captures the shadowed decl explicitly.
7909  CaptureLoc = getCaptureLocation(LSI, cast<VarDecl>(ShadowedDecl));
7910  if (CaptureLoc.isInvalid())
7911  WarningDiag = diag::warn_decl_shadow_uncaptured_local;
7912  } else {
7913  // Remember that this was shadowed so we can avoid the warning if the
7914  // shadowed decl isn't captured and the warning settings allow it.
7915  cast<LambdaScopeInfo>(getCurFunction())
7916  ->ShadowingDecls.push_back(
7917  {cast<VarDecl>(D), cast<VarDecl>(ShadowedDecl)});
7918  return;
7919  }
7920  }
7921 
7922  if (cast<VarDecl>(ShadowedDecl)->hasLocalStorage()) {
7923  // A variable can't shadow a local variable in an enclosing scope, if
7924  // they are separated by a non-capturing declaration context.
7925  for (DeclContext *ParentDC = NewDC;
7926  ParentDC && !ParentDC->Equals(OldDC);
7927  ParentDC = getLambdaAwareParentOfDeclContext(ParentDC)) {
7928  // Only block literals, captured statements, and lambda expressions
7929  // can capture; other scopes don't.
7930  if (!isa<BlockDecl>(ParentDC) && !isa<CapturedDecl>(ParentDC) &&
7931  !isLambdaCallOperator(ParentDC)) {
7932  return;
7933  }
7934  }
7935  }
7936  }
7937  }
7938 
7939  // Only warn about certain kinds of shadowing for class members.
7940  if (NewDC && NewDC->isRecord()) {
7941  // In particular, don't warn about shadowing non-class members.
7942  if (!OldDC->isRecord())
7943  return;
7944 
7945  // TODO: should we warn about static data members shadowing
7946  // static data members from base classes?
7947 
7948  // TODO: don't diagnose for inaccessible shadowed members.
7949  // This is hard to do perfectly because we might friend the
7950  // shadowing context, but that's just a false negative.
7951  }
7952 
7953 
7954  DeclarationName Name = R.getLookupName();
7955 
7956  // Emit warning and note.
7957  ShadowedDeclKind Kind = computeShadowedDeclKind(ShadowedDecl, OldDC);
7958  Diag(R.getNameLoc(), WarningDiag) << Name << Kind << OldDC;
7959  if (!CaptureLoc.isInvalid())
7960  Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7961  << Name << /*explicitly*/ 1;
7962  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7963 }
7964 
7965 /// Diagnose shadowing for variables shadowed in the lambda record \p LambdaRD
7966 /// when these variables are captured by the lambda.
7968  for (const auto &Shadow : LSI->ShadowingDecls) {
7969  const VarDecl *ShadowedDecl = Shadow.ShadowedDecl;
7970  // Try to avoid the warning when the shadowed decl isn't captured.
7971  SourceLocation CaptureLoc = getCaptureLocation(LSI, ShadowedDecl);
7972  const DeclContext *OldDC = ShadowedDecl->getDeclContext();
7973  Diag(Shadow.VD->getLocation(), CaptureLoc.isInvalid()
7974  ? diag::warn_decl_shadow_uncaptured_local
7975  : diag::warn_decl_shadow)
7976  << Shadow.VD->getDeclName()
7977  << computeShadowedDeclKind(ShadowedDecl, OldDC) << OldDC;
7978  if (!CaptureLoc.isInvalid())
7979  Diag(CaptureLoc, diag::note_var_explicitly_captured_here)
7980  << Shadow.VD->getDeclName() << /*explicitly*/ 0;
7981  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
7982  }
7983 }
7984 
7985 /// Check -Wshadow without the advantage of a previous lookup.
7987  if (Diags.isIgnored(diag::warn_decl_shadow, D->getLocation()))
7988  return;
7989 
7990  LookupResult R(*this, D->getDeclName(), D->getLocation(),
7992  LookupName(R, S);
7993  if (NamedDecl *ShadowedDecl = getShadowedDeclaration(D, R))
7994  CheckShadow(D, ShadowedDecl, R);
7995 }
7996 
7997 /// Check if 'E', which is an expression that is about to be modified, refers
7998 /// to a constructor parameter that shadows a field.
8000  // Quickly ignore expressions that can't be shadowing ctor parameters.
8001  if (!getLangOpts().CPlusPlus || ShadowingDecls.empty())
8002  return;
8003  E = E->IgnoreParenImpCasts();
8004  auto *DRE = dyn_cast<DeclRefExpr>(E);
8005  if (!DRE)
8006  return;
8007  const NamedDecl *D = cast<NamedDecl>(DRE->getDecl()->getCanonicalDecl());
8008  auto I = ShadowingDecls.find(D);
8009  if (I == ShadowingDecls.end())
8010  return;
8011  const NamedDecl *ShadowedDecl = I->second;
8012  const DeclContext *OldDC = ShadowedDecl->getDeclContext();
8013  Diag(Loc, diag::warn_modifying_shadowing_decl) << D << OldDC;
8014  Diag(D->getLocation(), diag::note_var_declared_here) << D;
8015  Diag(ShadowedDecl->getLocation(), diag::note_previous_declaration);
8016 
8017  // Avoid issuing multiple warnings about the same decl.
8018  ShadowingDecls.erase(I);
8019 }
8020 
8021 /// Check for conflict between this global or extern "C" declaration and
8022 /// previous global or extern "C" declarations. This is only used in C++.
8023 template<typename T>
8025  Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous) {
8026  assert(S.getLangOpts().CPlusPlus && "only C++ has extern \"C\"");
8027  NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName());
8028 
8029  if (!Prev && IsGlobal && !isIncompleteDeclExternC(S, ND)) {
8030  // The common case: this global doesn't conflict with any extern "C"
8031  // declaration.
8032  return false;
8033  }
8034 
8035  if (Prev) {
8036  if (!IsGlobal || isIncompleteDeclExternC(S, ND)) {
8037  // Both the old and new declarations have C language linkage. This is a
8038  // redeclaration.
8039  Previous.clear();
8040  Previous.addDecl(Prev);
8041  return true;
8042  }
8043 
8044  // This is a global, non-extern "C" declaration, and there is a previous
8045  // non-global extern "C" declaration. Diagnose if this is a variable
8046  // declaration.
8047  if (!isa<VarDecl>(ND))
8048  return false;
8049  } else {
8050  // The declaration is extern "C". Check for any declaration in the
8051  // translation unit which might conflict.
8052  if (IsGlobal) {
8053  // We have already performed the lookup into the translation unit.
8054  IsGlobal = false;
8055  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8056  I != E; ++I) {
8057  if (isa<VarDecl>(*I)) {
8058  Prev = *I;
8059  break;
8060  }
8061  }
8062  } else {
8064  S.Context.getTranslationUnitDecl()->lookup(ND->getDeclName());
8065  for (DeclContext::lookup_result::iterator I = R.begin(), E = R.end();
8066  I != E; ++I) {
8067  if (isa<VarDecl>(*I)) {
8068  Prev = *I;
8069  break;
8070  }
8071  // FIXME: If we have any other entity with this name in global scope,
8072  // the declaration is ill-formed, but that is a defect: it breaks the
8073  // 'stat' hack, for instance. Only variables can have mangled name
8074  // clashes with extern "C" declarations, so only they deserve a
8075  // diagnostic.
8076  }
8077  }
8078 
8079  if (!Prev)
8080  return false;
8081  }
8082 
8083  // Use the first declaration's location to ensure we point at something which
8084  // is lexically inside an extern "C" linkage-spec.
8085  assert(Prev && "should have found a previous declaration to diagnose");
8086  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Prev))
8087  Prev = FD->getFirstDecl();
8088  else
8089  Prev = cast<VarDecl>(Prev)->getFirstDecl();
8090 
8091  S.Diag(ND->getLocation(), diag::err_extern_c_global_conflict)
8092  << IsGlobal << ND;
8093  S.Diag(Prev->getLocation(), diag::note_extern_c_global_conflict)
8094  << IsGlobal;
8095  return false;
8096 }
8097 
8098 /// Apply special rules for handling extern "C" declarations. Returns \c true
8099 /// if we have found that this is a redeclaration of some prior entity.
8100 ///
8101 /// Per C++ [dcl.link]p6:
8102 /// Two declarations [for a function or variable] with C language linkage
8103 /// with the same name that appear in different scopes refer to the same
8104 /// [entity]. An entity with C language linkage shall not be declared with
8105 /// the same name as an entity in global scope.
8106 template<typename T>
8107 static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND,
8109  if (!S.getLangOpts().CPlusPlus) {
8110  // In C, when declaring a global variable, look for a corresponding 'extern'
8111  // variable declared in function scope. We don't need this in C++, because
8112  // we find local extern decls in the surrounding file-scope DeclContext.
8113  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit()) {
8114  if (NamedDecl *Prev = S.findLocallyScopedExternCDecl(ND->getDeclName())) {
8115  Previous.clear();
8116  Previous.addDecl(Prev);
8117  return true;
8118  }
8119  }
8120  return false;
8121  }
8122 
8123  // A declaration in the translation unit can conflict with an extern "C"
8124  // declaration.
8125  if (ND->getDeclContext()->getRedeclContext()->isTranslationUnit())
8126  return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/true, Previous);
8127 
8128  // An extern "C" declaration can conflict with a declaration in the
8129  // translation unit or can be a redeclaration of an extern "C" declaration
8130  // in another scope.
8131  if (isIncompleteDeclExternC(S,ND))
8132  return checkGlobalOrExternCConflict(S, ND, /*IsGlobal*/false, Previous);
8133 
8134  // Neither global nor extern "C": nothing to do.
8135  return false;
8136 }
8137 
8139  // If the decl is already known invalid, don't check it.
8140  if (NewVD->isInvalidDecl())
8141  return;
8142 
8143  QualType T = NewVD->getType();
8144 
8145  // Defer checking an 'auto' type until its initializer is attached.
8146  if (T->isUndeducedType())
8147  return;
8148 
8149  if (NewVD->hasAttrs())
8150  CheckAlignasUnderalignment(NewVD);
8151 
8152  if (T->isObjCObjectType()) {
8153  Diag(NewVD->getLocation(), diag::err_statically_allocated_object)
8154  << FixItHint::CreateInsertion(NewVD->getLocation(), "*");
8155  T = Context.getObjCObjectPointerType(T);
8156  NewVD->setType(T);
8157  }
8158 
8159  // Emit an error if an address space was applied to decl with local storage.
8160  // This includes arrays of objects with address space qualifiers, but not
8161  // automatic variables that point to other address spaces.
8162  // ISO/IEC TR 18037 S5.1.2
8163  if (!getLangOpts().OpenCL && NewVD->hasLocalStorage() &&
8165  Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 0;
8166  NewVD->setInvalidDecl();
8167  return;
8168  }
8169 
8170  // OpenCL v1.2 s6.8 - The static qualifier is valid only in program
8171  // scope.
8172  if (getLangOpts().OpenCLVersion == 120 &&
8173  !getOpenCLOptions().isAvailableOption("cl_clang_storage_class_specifiers",
8174  getLangOpts()) &&
8175  NewVD->isStaticLocal()) {
8176  Diag(NewVD->getLocation(), diag::err_static_function_scope);
8177  NewVD->setInvalidDecl();
8178  return;
8179  }
8180 
8181  if (getLangOpts().OpenCL) {
8182  if (!diagnoseOpenCLTypes(*this, NewVD))
8183  return;
8184 
8185  // OpenCL v2.0 s6.12.5 - The __block storage type is not supported.
8186  if (NewVD->hasAttr<BlocksAttr>()) {
8187  Diag(NewVD->getLocation(), diag::err_opencl_block_storage_type);
8188  return;
8189  }
8190 
8191  if (T->isBlockPointerType()) {
8192  // OpenCL v2.0 s6.12.5 - Any block declaration must be const qualified and
8193  // can't use 'extern' storage class.
8194  if (!T.isConstQualified()) {
8195  Diag(NewVD->getLocation(), diag::err_opencl_invalid_block_declaration)
8196  << 0 /*const*/;
8197  NewVD->setInvalidDecl();
8198  return;
8199  }
8200  if (NewVD->hasExternalStorage()) {
8201  Diag(NewVD->getLocation(), diag::err_opencl_extern_block_declaration);
8202  NewVD->setInvalidDecl();
8203  return;
8204  }
8205  }
8206 
8207  // FIXME: Adding local AS in C++ for OpenCL might make sense.
8208  if (NewVD->isFileVarDecl() || NewVD->isStaticLocal() ||
8209  NewVD->hasExternalStorage()) {
8210  if (!T->isSamplerT() && !T->isDependentType() &&
8213  getOpenCLOptions().areProgramScopeVariablesSupported(
8214  getLangOpts())))) {
8215  int Scope = NewVD->isStaticLocal() | NewVD->hasExternalStorage() << 1;
8216  if (getOpenCLOptions().areProgramScopeVariablesSupported(getLangOpts()))
8217  Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8218  << Scope << "global or constant";
8219  else
8220  Diag(NewVD->getLocation(), diag::err_opencl_global_invalid_addr_space)
8221  << Scope << "constant";
8222  NewVD->setInvalidDecl();
8223  return;
8224  }
8225  } else {
8227  Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8228  << 1 /*is any function*/ << "global";
8229  NewVD->setInvalidDecl();
8230  return;
8231  }
8234  FunctionDecl *FD = getCurFunctionDecl();
8235  // OpenCL v1.1 s6.5.2 and s6.5.3: no local or constant variables
8236  // in functions.
8237  if (FD && !FD->hasAttr<OpenCLKernelAttr>()) {
8239  Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8240  << 0 /*non-kernel only*/ << "constant";
8241  else
8242  Diag(NewVD->getLocation(), diag::err_opencl_function_variable)
8243  << 0 /*non-kernel only*/ << "local";
8244  NewVD->setInvalidDecl();
8245  return;
8246  }
8247  // OpenCL v2.0 s6.5.2 and s6.5.3: local and constant variables must be
8248  // in the outermost scope of a kernel function.
8249  if (FD && FD->hasAttr<OpenCLKernelAttr>()) {
8250  if (!getCurScope()->isFunctionScope()) {
8252  Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8253  << "constant";
8254  else
8255  Diag(NewVD->getLocation(), diag::err_opencl_addrspace_scope)
8256  << "local";
8257  NewVD->setInvalidDecl();
8258  return;
8259  }
8260  }
8261  } else if (T.getAddressSpace() != LangAS::opencl_private &&
8262  // If we are parsing a template we didn't deduce an addr
8263  // space yet.
8265  // Do not allow other address spaces on automatic variable.
8266  Diag(NewVD->getLocation(), diag::err_as_qualified_auto_decl) << 1;
8267  NewVD->setInvalidDecl();
8268  return;
8269  }
8270  }
8271  }
8272 
8273  if (NewVD->hasLocalStorage() && T.isObjCGCWeak()
8274  && !NewVD->hasAttr<BlocksAttr>()) {
8275  if (getLangOpts().getGC() != LangOptions::NonGC)
8276  Diag(NewVD->getLocation(), diag::warn_gc_attribute_weak_on_local);
8277  else {
8278  assert(!getLangOpts().ObjCAutoRefCount);
8279  Diag(NewVD->getLocation(), diag::warn_attribute_weak_on_local);
8280  }
8281  }
8282 
8283  bool isVM = T->isVariablyModifiedType();
8284  if (isVM || NewVD->hasAttr<CleanupAttr>() ||
8285  NewVD->hasAttr<BlocksAttr>())
8286  setFunctionHasBranchProtectedScope();
8287 
8288  if ((isVM && NewVD->hasLinkage()) ||
8289  (T->isVariableArrayType() && NewVD->hasGlobalStorage())) {
8290  bool SizeIsNegative;
8291  llvm::APSInt Oversized;
8293  NewVD->getTypeSourceInfo(), Context, SizeIsNegative, Oversized);
8294  QualType FixedT;
8295  if (FixedTInfo && T == NewVD->getTypeSourceInfo()->getType())
8296  FixedT = FixedTInfo->getType();
8297  else if (FixedTInfo) {
8298  // Type and type-as-written are canonically different. We need to fix up
8299  // both types separately.
8300  FixedT = TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative,
8301  Oversized);
8302  }
8303  if ((!FixedTInfo || FixedT.isNull()) && T->isVariableArrayType()) {
8304  const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
8305  // FIXME: This won't give the correct result for
8306  // int a[10][n];
8307  SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
8308 
8309  if (NewVD->isFileVarDecl())
8310  Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
8311  << SizeRange;
8312  else if (NewVD->isStaticLocal())
8313  Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
8314  << SizeRange;
8315  else
8316  Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
8317  << SizeRange;
8318  NewVD->setInvalidDecl();
8319  return;
8320  }
8321 
8322  if (!FixedTInfo) {
8323  if (NewVD->isFileVarDecl())
8324  Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
8325  else
8326  Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
8327  NewVD->setInvalidDecl();
8328  return;
8329  }
8330 
8331  Diag(NewVD->getLocation(), diag::ext_vla_folded_to_constant);
8332  NewVD->setType(FixedT);
8333  NewVD->setTypeSourceInfo(FixedTInfo);
8334  }
8335 
8336  if (T->isVoidType()) {
8337  // C++98 [dcl.stc]p5: The extern specifier can be applied only to the names
8338  // of objects and functions.
8339  if (NewVD->isThisDeclarationADefinition() || getLangOpts().CPlusPlus) {
8340  Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
8341  << T;
8342  NewVD->setInvalidDecl();
8343  return;
8344  }
8345  }
8346 
8347  if (!NewVD->hasLocalStorage() && NewVD->hasAttr<BlocksAttr>()) {
8348  Diag(NewVD->getLocation(), diag::err_block_on_nonlocal);
8349  NewVD->setInvalidDecl();
8350  return;
8351  }
8352 
8353  if (!NewVD->hasLocalStorage() && T->isSizelessType()) {
8354  Diag(NewVD->getLocation(), diag::err_sizeless_nonlocal) << T;
8355  NewVD->setInvalidDecl();
8356  return;
8357  }
8358 
8359  if (isVM && NewVD->hasAttr<BlocksAttr>()) {
8360  Diag(NewVD->getLocation(), diag::err_block_on_vm);
8361  NewVD->setInvalidDecl();
8362  return;
8363  }
8364 
8365  if (NewVD->isConstexpr() && !T->isDependentType() &&
8366  RequireLiteralType(NewVD->getLocation(), T,
8367  diag::err_constexpr_var_non_literal)) {
8368  NewVD->setInvalidDecl();
8369  return;
8370  }
8371 
8372  // PPC MMA non-pointer types are not allowed as non-local variable types.
8373  if (Context.getTargetInfo().getTriple().isPPC64() &&
8374  !NewVD->isLocalVarDecl() &&
8375  CheckPPCMMAType(T, NewVD->getLocation())) {
8376  NewVD->setInvalidDecl();
8377  return;
8378  }
8379 }
8380 
8381 /// Perform semantic checking on a newly-created variable
8382 /// declaration.
8383 ///
8384 /// This routine performs all of the type-checking required for a
8385 /// variable declaration once it has been built. It is used both to
8386 /// check variables after they have been parsed and their declarators
8387 /// have been translated into a declaration, and to check variables
8388 /// that have been instantiated from a template.
8389 ///
8390 /// Sets NewVD->isInvalidDecl() if an error was encountered.
8391 ///
8392 /// Returns true if the variable declaration is a redeclaration.
8394  CheckVariableDeclarationType(NewVD);
8395 
8396  // If the decl is already known invalid, don't check it.
8397  if (NewVD->isInvalidDecl())
8398  return false;
8399 
8400  // If we did not find anything by this name, look for a non-visible
8401  // extern "C" declaration with the same name.
8402  if (Previous.empty() &&
8404  Previous.setShadowed();
8405 
8406  if (!Previous.empty()) {
8407  MergeVarDecl(NewVD, Previous);
8408  return true;
8409  }
8410  return false;
8411 }
8412 
8413 /// AddOverriddenMethods - See if a method overrides any in the base classes,
8414 /// and if so, check that it's a valid override and remember it.
8417 
8418  // Look for methods in base classes that this method might override.
8419  CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
8420  /*DetectVirtual=*/false);
8421  auto VisitBase = [&] (const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
8422  CXXRecordDecl *BaseRecord = Specifier->getType()->getAsCXXRecordDecl();
8423  DeclarationName Name = MD->getDeclName();
8424 
8425  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8426  // We really want to find the base class destructor here.
8427  QualType T = Context.getTypeDeclType(BaseRecord);
8428  CanQualType CT = Context.getCanonicalType(T);
8429  Name = Context.DeclarationNames.getCXXDestructorName(CT);
8430  }
8431 
8432  for (NamedDecl *BaseND : BaseRecord->lookup(Name)) {
8433  CXXMethodDecl *BaseMD =
8434  dyn_cast<CXXMethodDecl>(BaseND->getCanonicalDecl());
8435  if (!BaseMD || !BaseMD->isVirtual() ||
8436  IsOverload(MD, BaseMD, /*UseMemberUsingDeclRules=*/false,
8437  /*ConsiderCudaAttrs=*/true,
8438  // C++2a [class.virtual]p2 does not consider requires
8439  // clauses when overriding.
8440  /*ConsiderRequiresClauses=*/false))
8441  continue;
8442 
8443  if (Overridden.insert(BaseMD).second) {
8444  MD->addOverriddenMethod(BaseMD);
8445  CheckOverridingFunctionReturnType(MD, BaseMD);
8446  CheckOverridingFunctionAttributes(MD, BaseMD);
8447  CheckOverridingFunctionExceptionSpec(MD, BaseMD);
8448  CheckIfOverriddenFunctionIsMarkedFinal(MD, BaseMD);
8449  }
8450 
8451  // A method can only override one function from each base class. We
8452  // don't track indirectly overridden methods from bases of bases.
8453  return true;
8454  }
8455 
8456  return false;
8457  };
8458 
8459  DC->lookupInBases(VisitBase, Paths);
8460  return !Overridden.empty();
8461 }
8462 
8463 namespace {
8464  // Struct for holding all of the extra arguments needed by
8465  // DiagnoseInvalidRedeclaration to call Sema::ActOnFunctionDeclarator.
8466  struct ActOnFDArgs {
8467  Scope *S;
8468  Declarator &D;
8469  MultiTemplateParamsArg TemplateParamLists;
8470  bool AddToScope;
8471  };
8472 } // end anonymous namespace
8473 
8474 namespace {
8475 
8476 // Callback to only accept typo corrections that have a non-zero edit distance.
8477 // Also only accept corrections that have the same parent decl.
8478 class DifferentNameValidatorCCC final : public CorrectionCandidateCallback {
8479  public:
8480  DifferentNameValidatorCCC(ASTContext &Context, FunctionDecl *TypoFD,
8482  : Context(Context), OriginalFD(TypoFD),
8483  ExpectedParent(Parent ? Parent->getCanonicalDecl() : nullptr) {}
8484 
8485  bool ValidateCandidate(const TypoCorrection &candidate) override {
8486  if (candidate.getEditDistance() == 0)
8487  return false;
8488 
8489  SmallVector<unsigned, 1> MismatchedParams;
8490  for (TypoCorrection::const_decl_iterator CDecl = candidate.begin(),
8491  CDeclEnd = candidate.end();
8492  CDecl != CDeclEnd; ++CDecl) {
8493  FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8494 
8495  if (FD && !FD->hasBody() &&
8496  hasSimilarParameters(Context, FD, OriginalFD, MismatchedParams)) {
8497  if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
8498  CXXRecordDecl *Parent = MD->getParent();
8499  if (Parent && Parent->getCanonicalDecl() == ExpectedParent)
8500  return true;
8501  } else if (!ExpectedParent) {
8502  return true;
8503  }
8504  }
8505  }
8506 
8507  return false;
8508  }
8509 
8510  std::unique_ptr<CorrectionCandidateCallback> clone() override {
8511  return std::make_unique<DifferentNameValidatorCCC>(*this);
8512  }
8513 
8514  private:
8515  ASTContext &Context;
8516  FunctionDecl *OriginalFD;
8517  CXXRecordDecl *ExpectedParent;
8518 };
8519 
8520 } // end anonymous namespace
8521 
8523  TypoCorrectedFunctionDefinitions.insert(F);
8524 }
8525 
8526 /// Generate diagnostics for an invalid function redeclaration.
8527 ///
8528 /// This routine handles generating the diagnostic messages for an invalid
8529 /// function redeclaration, including finding possible similar declarations
8530 /// or performing typo correction if there are no previous declarations with
8531 /// the same name.
8532 ///
8533 /// Returns a NamedDecl iff typo correction was performed and substituting in
8534 /// the new declaration name does not cause new errors.
8536  Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD,
8537  ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S) {
8538  DeclarationName Name = NewFD->getDeclName();
8539  DeclContext *NewDC = NewFD->getDeclContext();
8540  SmallVector<unsigned, 1> MismatchedParams;
8542  TypoCorrection Correction;
8543  bool IsDefinition = ExtraArgs.D.isFunctionDefinition();
8544  unsigned DiagMsg =
8545  IsLocalFriend ? diag::err_no_matching_local_friend :
8546  NewFD->getFriendObjectKind() ? diag::err_qualified_friend_no_match :
8547  diag::err_member_decl_does_not_match;
8548  LookupResult Prev(SemaRef, Name, NewFD->getLocation(),
8549  IsLocalFriend ? Sema::LookupLocalFriendName
8552 
8553  NewFD->setInvalidDecl();
8554  if (IsLocalFriend)
8555  SemaRef.LookupName(Prev, S);
8556  else
8557  SemaRef.LookupQualifiedName(Prev, NewDC);
8558  assert(!Prev.isAmbiguous() &&
8559  "Cannot have an ambiguity in previous-declaration lookup");
8560  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
8561  DifferentNameValidatorCCC CCC(SemaRef.Context, NewFD,
8562  MD ? MD->getParent() : nullptr);
8563  if (!Prev.empty()) {
8564  for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
8565  Func != FuncEnd; ++Func) {
8566  FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func);
8567  if (FD &&
8568  hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8569  // Add 1 to the index so that 0 can mean the mismatch didn't
8570  // involve a parameter
8571  unsigned ParamNum =
8572  MismatchedParams.empty() ? 0 : MismatchedParams.front() + 1;
8573  NearMatches.push_back(std::make_pair(FD, ParamNum));
8574  }
8575  }
8576  // If the qualified name lookup yielded nothing, try typo correction
8577  } else if ((Correction = SemaRef.CorrectTypo(
8578  Prev.getLookupNameInfo(), Prev.getLookupKind(), S,
8579  &ExtraArgs.D.getCXXScopeSpec(), CCC, Sema::CTK_ErrorRecovery,
8580  IsLocalFriend ? nullptr : NewDC))) {
8581  // Set up everything for the call to ActOnFunctionDeclarator
8582  ExtraArgs.D.SetIdentifier(Correction.getCorrectionAsIdentifierInfo(),
8583  ExtraArgs.D.getIdentifierLoc());
8584  Previous.clear();
8585  Previous.setLookupName(Correction.getCorrection());
8586  for (TypoCorrection::decl_iterator CDecl = Correction.begin(),
8587  CDeclEnd = Correction.end();
8588  CDecl != CDeclEnd; ++CDecl) {
8589  FunctionDecl *FD = dyn_cast<FunctionDecl>(*CDecl);
8590  if (FD && !FD->hasBody() &&
8591  hasSimilarParameters(SemaRef.Context, FD, NewFD, MismatchedParams)) {
8592  Previous.addDecl(FD);
8593  }
8594  }
8595  bool wasRedeclaration = ExtraArgs.D.isRedeclaration();
8596 
8597  NamedDecl *Result;
8598  // Retry building the function declaration with the new previous
8599  // declarations, and with errors suppressed.
8600  {
8601  // Trap errors.
8602  Sema::SFINAETrap Trap(SemaRef);
8603 
8604  // TODO: Refactor ActOnFunctionDeclarator so that we can call only the
8605  // pieces need to verify the typo-corrected C++ declaration and hopefully
8606  // eliminate the need for the parameter pack ExtraArgs.
8607  Result = SemaRef.ActOnFunctionDeclarator(
8608  ExtraArgs.S, ExtraArgs.D,
8609  Correction.getCorrectionDecl()->getDeclContext(),
8610  NewFD->getTypeSourceInfo(), Previous, ExtraArgs.TemplateParamLists,
8611  ExtraArgs.AddToScope);
8612 
8613  if (Trap.hasErrorOccurred())
8614  Result = nullptr;
8615  }
8616 
8617  if (Result) {
8618  // Determine which correction we picked.
8619  Decl *Canonical = Result->getCanonicalDecl();
8620  for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
8621  I != E; ++I)
8622  if ((*I)->getCanonicalDecl() == Canonical)
8623  Correction.setCorrectionDecl(*I);
8624 
8625  // Let Sema know about the correction.
8626  SemaRef.MarkTypoCorrectedFunctionDefinition(Result);
8627  SemaRef.diagnoseTypo(
8628  Correction,
8629  SemaRef.PDiag(IsLocalFriend
8630  ? diag::err_no_matching_local_friend_suggest
8631  : diag::err_member_decl_does_not_match_suggest)
8632  << Name << NewDC << IsDefinition);
8633  return Result;
8634  }
8635 
8636  // Pretend the typo correction never occurred
8637  ExtraArgs.D.SetIdentifier(Name.getAsIdentifierInfo(),
8638  ExtraArgs.D.getIdentifierLoc());
8639  ExtraArgs.D.setRedeclaration(wasRedeclaration);
8640  Previous.clear();
8641  Previous.setLookupName(Name);
8642  }
8643 
8644  SemaRef.Diag(NewFD->getLocation(), DiagMsg)
8645  << Name << NewDC << IsDefinition << NewFD->getLocation();
8646 
8647  bool NewFDisConst = false;
8648  if (CXXMethodDecl *NewMD = dyn_cast<CXXMethodDecl>(NewFD))
8649  NewFDisConst = NewMD->isConst();
8650 
8651  for (SmallVectorImpl<std::pair<FunctionDecl *, unsigned> >::iterator
8652  NearMatch = NearMatches.begin(), NearMatchEnd = NearMatches.end();
8653  NearMatch != NearMatchEnd; ++NearMatch) {
8654  FunctionDecl *FD = NearMatch->first;
8655  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
8656  bool FDisConst = MD && MD->isConst();
8657  bool IsMember = MD || !IsLocalFriend;
8658 
8659  // FIXME: These notes are poorly worded for the local friend case.
8660  if (unsigned Idx = NearMatch->second) {
8661  ParmVarDecl *FDParam = FD->getParamDecl(Idx-1);
8662  SourceLocation Loc = FDParam->getTypeSpecStartLoc();
8663  if (Loc.isInvalid()) Loc = FD->getLocation();
8664  SemaRef.Diag(Loc, IsMember ? diag::note_member_def_close_param_match
8665  : diag::note_local_decl_close_param_match)
8666  << Idx << FDParam->getType()
8667  << NewFD->getParamDecl(Idx - 1)->getType();
8668  } else if (FDisConst != NewFDisConst) {
8669  SemaRef.Diag(FD->getLocation(), diag::note_member_def_close_const_match)
8670  << NewFDisConst << FD->getSourceRange().getEnd()
8671  << (NewFDisConst
8672  ? FixItHint::CreateRemoval(ExtraArgs.D.getFunctionTypeInfo()
8673  .getConstQualifierLoc())
8674  : FixItHint::CreateInsertion(ExtraArgs.D.getFunctionTypeInfo()
8675  .getRParenLoc()
8676  .getLocWithOffset(1),
8677  " const"));
8678  } else
8679  SemaRef.Diag(FD->getLocation(),
8680  IsMember ? diag::note_member_def_close_match
8681  : diag::note_local_decl_close_match);
8682  }
8683  return nullptr;
8684 }
8685 
8687  switch (D.getDeclSpec().getStorageClassSpec()) {
8688  default: llvm_unreachable("Unknown storage class!");
8689  case DeclSpec::SCS_auto:
8691  case DeclSpec::SCS_mutable:
8692  SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8693  diag::err_typecheck_sclass_func);
8695  D.setInvalidType();
8696  break;
8697  case DeclSpec::SCS_unspecified: break;
8698  case DeclSpec::SCS_extern:
8700  return SC_None;
8701  return SC_Extern;
8702  case DeclSpec::SCS_static: {
8703  if (SemaRef.CurContext->getRedeclContext()->isFunctionOrMethod()) {
8704  // C99 6.7.1p5:
8705  // The declaration of an identifier for a function that has
8706  // block scope shall have no explicit storage-class specifier
8707  // other than extern
8708  // See also (C++ [dcl.stc]p4).
8709  SemaRef.Diag(D.getDeclSpec().getStorageClassSpecLoc(),
8710  diag::err_static_block_func);
8711  break;
8712  } else
8713  return SC_Static;
8714  }
8716  }
8717 
8718  // No explicit storage class has already been returned
8719  return SC_None;
8720 }
8721 
8723  DeclContext *DC, QualType &R,
8724  TypeSourceInfo *TInfo,
8725  StorageClass SC,
8726  bool &IsVirtualOkay) {
8727  DeclarationNameInfo NameInfo = SemaRef.GetNameForDeclarator(D);
8728  DeclarationName Name = NameInfo.getName();
8729 
8730  FunctionDecl *NewFD = nullptr;
8731  bool isInline = D.getDeclSpec().isInlineSpecified();
8732 
8733  if (!SemaRef.getLangOpts().CPlusPlus) {
8734  // Determine whether the function was written with a
8735  // prototype. This true when:
8736  // - there is a prototype in the declarator, or
8737  // - the type R of the function is some kind of typedef or other non-
8738  // attributed reference to a type name (which eventually refers to a
8739  // function type).
8740  bool HasPrototype =
8743 
8744  NewFD = FunctionDecl::Create(
8745  SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8746  SemaRef.getCurFPFeatures().isFPConstrained(), isInline, HasPrototype,
8748  /*TrailingRequiresClause=*/nullptr);
8749  if (D.isInvalidType())
8750  NewFD->setInvalidDecl();
8751 
8752  return NewFD;
8753  }
8754 
8756 
8757  ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
8758  if (ConstexprKind == ConstexprSpecKind::Constinit) {
8759  SemaRef.Diag(D.getDeclSpec().getConstexprSpecLoc(),
8760  diag::err_constexpr_wrong_decl_kind)
8761  << static_cast<int>(ConstexprKind);
8762  ConstexprKind = ConstexprSpecKind::Unspecified;
8764  }
8765  Expr *TrailingRequiresClause = D.getTrailingRequiresClause();
8766 
8767  // Check that the return type is not an abstract class type.
8768  // For record types, this is done by the AbstractClassUsageDiagnoser once
8769  // the class has been completely parsed.
8770  if (!DC->isRecord() &&
8771  SemaRef.RequireNonAbstractType(
8773  diag::err_abstract_type_in_decl, SemaRef.AbstractReturnType))
8774  D.setInvalidType();
8775 
8776  if (Name.getNameKind() == DeclarationName::CXXConstructorName) {
8777  // This is a C++ constructor declaration.
8778  assert(DC->isRecord() &&
8779  "Constructors can only be declared in a member context");
8780 
8781  R = SemaRef.CheckConstructorDeclarator(D, R, SC);
8783  SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8785  isInline, /*isImplicitlyDeclared=*/false, ConstexprKind,
8786  InheritedConstructor(), TrailingRequiresClause);
8787 
8788  } else if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
8789  // This is a C++ destructor declaration.
8790  if (DC->isRecord()) {
8791  R = SemaRef.CheckDestructorDeclarator(D, R, SC);
8792  CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
8794  SemaRef.Context, Record, D.getBeginLoc(), NameInfo, R, TInfo,
8795  SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8796  /*isImplicitlyDeclared=*/false, ConstexprKind,
8797  TrailingRequiresClause);
8798 
8799  // If the destructor needs an implicit exception specification, set it
8800  // now. FIXME: It'd be nice to be able to create the right type to start
8801  // with, but the type needs to reference the destructor declaration.
8802  if (SemaRef.getLangOpts().CPlusPlus11)
8803  SemaRef.AdjustDestructorExceptionSpec(NewDD);
8804 
8805  IsVirtualOkay = true;
8806  return NewDD;
8807 
8808  } else {
8809  SemaRef.Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
8810  D.setInvalidType();
8811 
8812  // Create a FunctionDecl to satisfy the function definition parsing
8813  // code path.
8814  return FunctionDecl::Create(
8815  SemaRef.Context, DC, D.getBeginLoc(), D.getIdentifierLoc(), Name, R,
8816  TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8817  /*hasPrototype=*/true, ConstexprKind, TrailingRequiresClause);
8818  }
8819 
8820  } else if (Name.getNameKind() == DeclarationName::CXXConversionFunctionName) {
8821  if (!DC->isRecord()) {
8822  SemaRef.Diag(D.getIdentifierLoc(),
8823  diag::err_conv_function_not_member);
8824  return nullptr;
8825  }
8826 
8827  SemaRef.CheckConversionDeclarator(D, R, SC);
8828  if (D.isInvalidType())
8829  return nullptr;
8830 
8831  IsVirtualOkay = true;
8833  SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8834  TInfo, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8835  ExplicitSpecifier, ConstexprKind, SourceLocation(),
8836  TrailingRequiresClause);
8837 
8838  } else if (Name.getNameKind() == DeclarationName::CXXDeductionGuideName) {
8839  if (TrailingRequiresClause)
8840  SemaRef.Diag(TrailingRequiresClause->getBeginLoc(),
8841  diag::err_trailing_requires_clause_on_deduction_guide)
8842  << TrailingRequiresClause->getSourceRange();
8843  SemaRef.CheckDeductionGuideDeclarator(D, R, SC);
8844 
8845  return CXXDeductionGuideDecl::Create(SemaRef.Context, DC, D.getBeginLoc(),
8846  ExplicitSpecifier, NameInfo, R, TInfo,
8847  D.getEndLoc());
8848  } else if (DC->isRecord()) {
8849  // If the name of the function is the same as the name of the record,
8850  // then this must be an invalid constructor that has a return type.
8851  // (The parser checks for a return type and makes the declarator a
8852  // constructor if it has no return type).
8853  if (Name.getAsIdentifierInfo() &&
8854  Name.getAsIdentifierInfo() == cast<CXXRecordDecl>(DC)->getIdentifier()){
8855  SemaRef.Diag(D.getIdentifierLoc(), diag::err_constructor_return_type)
8857  << SourceRange(D.getIdentifierLoc());
8858  return nullptr;
8859  }
8860 
8861  // This is a C++ method declaration.
8863  SemaRef.Context, cast<CXXRecordDecl>(DC), D.getBeginLoc(), NameInfo, R,
8864  TInfo, SC, SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8865  ConstexprKind, SourceLocation(), TrailingRequiresClause);
8866  IsVirtualOkay = !Ret->isStatic();
8867  return Ret;
8868  } else {
8869  bool isFriend =
8870  SemaRef.getLangOpts().CPlusPlus && D.getDeclSpec().isFriendSpecified();
8871  if (!isFriend && SemaRef.CurContext->isRecord())
8872  return nullptr;
8873 
8874  // Determine whether the function was written with a
8875  // prototype. This true when:
8876  // - we're in C++ (where every function has a prototype),
8877  return FunctionDecl::Create(
8878  SemaRef.Context, DC, D.getBeginLoc(), NameInfo, R, TInfo, SC,
8879  SemaRef.getCurFPFeatures().isFPConstrained(), isInline,
8880  true /*HasPrototype*/, ConstexprKind, TrailingRequiresClause);
8881  }
8882 }
8883 
8891 };
8892 
8894  // Size dependent types are just typedefs to normal integer types
8895  // (e.g. unsigned long), so we cannot distinguish them from other typedefs to
8896  // integers other than by their names.
8897  StringRef SizeTypeNames[] = {"size_t", "intptr_t", "uintptr_t", "ptrdiff_t"};
8898 
8899  // Remove typedefs one by one until we reach a typedef
8900  // for a size dependent type.
8901  QualType DesugaredTy = Ty;
8902  do {
8903  ArrayRef<StringRef> Names(SizeTypeNames);
8904  auto Match = llvm::find(Names, DesugaredTy.getUnqualifiedType().getAsString());
8905  if (Names.end() != Match)
8906  return true;
8907 
8908  Ty = DesugaredTy;
8909  DesugaredTy = Ty.getSingleStepDesugaredType(C);
8910  } while (DesugaredTy != Ty);
8911 
8912  return false;
8913 }
8914 
8916  if (PT->isDependentType())
8917  return InvalidKernelParam;
8918 
8919  if (PT->isPointerType() || PT->isReferenceType()) {
8920  QualType PointeeType = PT->getPointeeType();
8921  if (PointeeType.getAddressSpace() == LangAS::opencl_generic ||
8922  PointeeType.getAddressSpace() == LangAS::opencl_private ||
8923  PointeeType.getAddressSpace() == LangAS::Default)
8925 
8926  if (PointeeType->isPointerType()) {
8927  // This is a pointer to pointer parameter.
8928  // Recursively check inner type.
8929  OpenCLParamType ParamKind = getOpenCLKernelParameterType(S, PointeeType);
8930  if (ParamKind == InvalidAddrSpacePtrKernelParam ||
8931  ParamKind == InvalidKernelParam)
8932  return ParamKind;
8933 
8934  return PtrPtrKernelParam;
8935  }
8936 
8937  // C++ for OpenCL v1.0 s2.4:
8938  // Moreover the types used in parameters of the kernel functions must be:
8939  // Standard layout types for pointer parameters. The same applies to
8940  // reference if an implementation supports them in kernel parameters.
8941  if (S.getLangOpts().OpenCLCPlusPlus &&
8943  "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8944  !PointeeType->isAtomicType() && !PointeeType->isVoidType() &&
8945  !PointeeType->isStandardLayoutType())
8946  return InvalidKernelParam;
8947 
8948  return PtrKernelParam;
8949  }
8950 
8951  // OpenCL v1.2 s6.9.k:
8952  // Arguments to kernel functions in a program cannot be declared with the
8953  // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
8954  // uintptr_t or a struct and/or union that contain fields declared to be one
8955  // of these built-in scalar types.
8957  return InvalidKernelParam;
8958 
8959  if (PT->isImageType())
8960  return PtrKernelParam;
8961 
8962  if (PT->isBooleanType() || PT->isEventT() || PT->isReserveIDT())
8963  return InvalidKernelParam;
8964 
8965  // OpenCL extension spec v1.2 s9.5:
8966  // This extension adds support for half scalar and vector types as built-in
8967  // types that can be used for arithmetic operations, conversions etc.
8968  if (!S.getOpenCLOptions().isAvailableOption("cl_khr_fp16", S.getLangOpts()) &&
8969  PT->isHalfType())
8970  return InvalidKernelParam;
8971 
8972  // Look into an array argument to check if it has a forbidden type.
8973  if (PT->isArrayType()) {
8974  const Type *UnderlyingTy = PT->getPointeeOrArrayElementType();
8975  // Call ourself to check an underlying type of an array. Since the
8976  // getPointeeOrArrayElementType returns an innermost type which is not an
8977  // array, this recursive call only happens once.
8978  return getOpenCLKernelParameterType(S, QualType(UnderlyingTy, 0));
8979  }
8980 
8981  // C++ for OpenCL v1.0 s2.4:
8982  // Moreover the types used in parameters of the kernel functions must be:
8983  // Trivial and standard-layout types C++17 [basic.types] (plain old data
8984  // types) for parameters passed by value;
8985  if (S.getLangOpts().OpenCLCPlusPlus &&
8987  "__cl_clang_non_portable_kernel_param_types", S.getLangOpts()) &&
8988  !PT->isOpenCLSpecificType() && !PT.isPODType(S.Context))
8989  return InvalidKernelParam;
8990 
8991  if (PT->isRecordType())
8992  return RecordKernelParam;
8993 
8994  return ValidKernelParam;
8995 }
8996 
8998  Sema &S,
8999  Declarator &D,
9000  ParmVarDecl *Param,
9001  llvm::SmallPtrSetImpl<const Type *> &ValidTypes) {
9002  QualType PT = Param->getType();
9003 
9004  // Cache the valid types we encounter to avoid rechecking structs that are
9005  // used again
9006  if (ValidTypes.count(PT.getTypePtr()))
9007  return;
9008 
9009  switch (getOpenCLKernelParameterType(S, PT)) {
9010  case PtrPtrKernelParam:
9011  // OpenCL v3.0 s6.11.a:
9012  // A kernel function argument cannot be declared as a pointer to a pointer
9013  // type. [...] This restriction only applies to OpenCL C 1.2 or below.
9014  if (S.getLangOpts().getOpenCLCompatibleVersion() <= 120) {
9015  S.Diag(Param->getLocation(), diag::err_opencl_ptrptr_kernel_param);
9016  D.setInvalidType();
9017  return;
9018  }
9019 
9020  ValidTypes.insert(PT.getTypePtr());
9021  return;
9022 
9024  // OpenCL v1.0 s6.5:
9025  // __kernel function arguments declared to be a pointer of a type can point
9026  // to one of the following address spaces only : __global, __local or
9027  // __constant.
9028  S.Diag(Param->getLocation(), diag::err_kernel_arg_address_space);
9029  D.setInvalidType();
9030  return;
9031 
9032  // OpenCL v1.2 s6.9.k:
9033  // Arguments to kernel functions in a program cannot be declared with the
9034  // built-in scalar types bool, half, size_t, ptrdiff_t, intptr_t, and
9035  // uintptr_t or a struct and/or union that contain fields declared to be
9036  // one of these built-in scalar types.
9037 
9038  case InvalidKernelParam:
9039  // OpenCL v1.2 s6.8 n:
9040  // A kernel function argument cannot be declared
9041  // of event_t type.
9042  // Do not diagnose half type since it is diagnosed as invalid argument
9043  // type for any function elsewhere.
9044  if (!PT->isHalfType()) {
9045  S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9046 
9047  // Explain what typedefs are involved.
9048  const TypedefType *Typedef = nullptr;
9049  while ((Typedef = PT->getAs<TypedefType>())) {
9050  SourceLocation Loc = Typedef->getDecl()->getLocation();
9051  // SourceLocation may be invalid for a built-in type.
9052  if (Loc.isValid())
9053  S.Diag(Loc, diag::note_entity_declared_at) << PT;
9054  PT = Typedef->desugar();
9055  }
9056  }
9057 
9058  D.setInvalidType();
9059  return;
9060 
9061  case PtrKernelParam:
9062  case ValidKernelParam:
9063  ValidTypes.insert(PT.getTypePtr());
9064  return;
9065 
9066  case RecordKernelParam:
9067  break;
9068  }
9069 
9070  // Track nested structs we will inspect
9071  SmallVector<const Decl *, 4> VisitStack;
9072 
9073  // Track where we are in the nested structs. Items will migrate from
9074  // VisitStack to HistoryStack as we do the DFS for bad field.
9075  SmallVector<const FieldDecl *, 4> HistoryStack;
9076  HistoryStack.push_back(nullptr);
9077 
9078  // At this point we already handled everything except of a RecordType or
9079  // an ArrayType of a RecordType.
9080  assert((PT->isArrayType() || PT->isRecordType()) && "Unexpected type.");
9081  const RecordType *RecTy =
9083  const RecordDecl *OrigRecDecl = RecTy->getDecl();
9084 
9085  VisitStack.push_back(RecTy->getDecl());
9086  assert(VisitStack.back() && "First decl null?");
9087 
9088  do {
9089  const Decl *Next = VisitStack.pop_back_val();
9090  if (!Next) {
9091  assert(!HistoryStack.empty());
9092  // Found a marker, we have gone up a level
9093  if (const FieldDecl *Hist = HistoryStack.pop_back_val())
9094  ValidTypes.insert(Hist->getType().getTypePtr());
9095 
9096  continue;
9097  }
9098 
9099  // Adds everything except the original parameter declaration (which is not a
9100  // field itself) to the history stack.
9101  const RecordDecl *RD;
9102  if (const FieldDecl *Field = dyn_cast<FieldDecl>(Next)) {
9103  HistoryStack.push_back(Field);
9104 
9105  QualType FieldTy = Field->getType();
9106  // Other field types (known to be valid or invalid) are handled while we
9107  // walk around RecordDecl::fields().
9108  assert((FieldTy->isArrayType() || FieldTy->isRecordType()) &&
9109  "Unexpected type.");
9110  const Type *FieldRecTy = FieldTy->getPointeeOrArrayElementType();
9111 
9112  RD = FieldRecTy->castAs<RecordType>()->getDecl();
9113  } else {
9114  RD = cast<RecordDecl>(Next);
9115  }
9116 
9117  // Add a null marker so we know when we've gone back up a level
9118  VisitStack.push_back(nullptr);
9119 
9120  for (const auto *FD : RD->fields()) {
9121  QualType QT = FD->getType();
9122 
9123  if (ValidTypes.count(QT.getTypePtr()))
9124  continue;
9125 
9126  OpenCLParamType ParamType = getOpenCLKernelParameterType(S, QT);
9127  if (ParamType == ValidKernelParam)
9128  continue;
9129 
9130  if (ParamType == RecordKernelParam) {
9131  VisitStack.push_back(FD);
9132  continue;
9133  }
9134 
9135  // OpenCL v1.2 s6.9.p:
9136  // Arguments to kernel functions that are declared to be a struct or union
9137  // do not allow OpenCL objects to be passed as elements of the struct or
9138  // union.
9139  if (ParamType == PtrKernelParam || ParamType == PtrPtrKernelParam ||
9140  ParamType == InvalidAddrSpacePtrKernelParam) {
9141  S.Diag(Param->getLocation(),
9142  diag::err_record_with_pointers_kernel_param)
9143  << PT->isUnionType()
9144  << PT;
9145  } else {
9146  S.Diag(Param->getLocation(), diag::err_bad_kernel_param_type) << PT;
9147  }
9148 
9149  S.Diag(OrigRecDecl->getLocation(), diag::note_within_field_of_type)
9150  << OrigRecDecl->getDeclName();
9151 
9152  // We have an error, now let's go back up through history and show where
9153  // the offending field came from
9155  I = HistoryStack.begin() + 1,
9156  E = HistoryStack.end();
9157  I != E; ++I) {
9158  const FieldDecl *OuterField = *I;
9159  S.Diag(OuterField->getLocation(), diag::note_within_field_of_type)
9160  << OuterField->getType();
9161  }
9162 
9163  S.Diag(FD->getLocation(), diag::note_illegal_field_declared_here)
9164  << QT->isPointerType()
9165  << QT;
9166  D.setInvalidType();
9167  return;
9168  }
9169  } while (!VisitStack.empty());
9170 }
9171 
9172 /// Find the DeclContext in which a tag is implicitly declared if we see an
9173 /// elaborated type specifier in the specified context, and lookup finds
9174 /// nothing.
9176  while (!DC->isFileContext() && !DC->isFunctionOrMethod())
9177  DC = DC->getParent();
9178  return DC;
9179 }
9180 
9181 /// Find the Scope in which a tag is implicitly declared if we see an
9182 /// elaborated type specifier in the specified context, and lookup finds
9183 /// nothing.
9184 static Scope *getTagInjectionScope(Scope *S, const LangOptions &LangOpts) {
9185  while (S->isClassScope() ||
9186  (LangOpts.CPlusPlus &&
9187  S->isFunctionPrototypeScope()) ||
9188  ((S->getFlags() & Scope::DeclScope) == 0) ||
9189  (S->getEntity() && S->getEntity()->isTransparentContext()))
9190  S = S->getParent();
9191  return S;
9192 }
9193 
9194 NamedDecl*
9197  MultiTemplateParamsArg TemplateParamListsRef,
9198  bool &AddToScope) {
9199  QualType R = TInfo->getType();
9200 
9201  assert(R->isFunctionType());
9203  Diag(D.getIdentifierLoc(), diag::err_function_decl_cmse_ns_call);
9204 
9205  SmallVector<TemplateParameterList *, 4> TemplateParamLists;
9206  llvm::append_range(TemplateParamLists, TemplateParamListsRef);
9208  if (!TemplateParamLists.empty() &&
9209  Invented->getDepth() == TemplateParamLists.back()->getDepth())
9210  TemplateParamLists.back() = Invented;
9211  else
9212  TemplateParamLists.push_back(Invented);
9213  }
9214 
9215  // TODO: consider using NameInfo for diagnostic.
9216  DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
9217  DeclarationName Name = NameInfo.getName();
9218  StorageClass SC = getFunctionStorageClass(*this, D);
9219 
9222  diag::err_invalid_thread)
9223  << DeclSpec::getSpecifierName(TSCS);
9224 
9226  adjustMemberFunctionCC(R, D.isStaticMember(), D.isCtorOrDtor(),
9227  D.getIdentifierLoc());
9228 
9229  bool isFriend = false;
9230  FunctionTemplateDecl *FunctionTemplate = nullptr;
9231  bool isMemberSpecialization = false;
9232  bool isFunctionTemplateSpecialization = false;
9233 
9234  bool isDependentClassScopeExplicitSpecialization = false;
9235  bool HasExplicitTemplateArgs = false;
9236  TemplateArgumentListInfo TemplateArgs;
9237 
9238  bool isVirtualOkay = false;
9239 
9240  DeclContext *OriginalDC = DC;
9241  bool IsLocalExternDecl = adjustContextForLocalExternDecl(DC);
9242 
9243  FunctionDecl *NewFD = CreateNewFunctionDecl(*this, D, DC, R, TInfo, SC,
9244  isVirtualOkay);
9245  if (!NewFD) return nullptr;
9246 
9247  if (OriginalLexicalContext && OriginalLexicalContext->isObjCContainer())
9249 
9250  // Set the lexical context. If this is a function-scope declaration, or has a
9251  // C++ scope specifier, or is the object of a friend declaration, the lexical
9252  // context will be different from the semantic context.
9253  NewFD->setLexicalDeclContext(CurContext);
9254 
9255  if (IsLocalExternDecl)
9256  NewFD->setLocalExternDecl();
9257 
9258  if (getLangOpts().CPlusPlus) {
9259  bool isInline = D.getDeclSpec().isInlineSpecified();
9260  bool isVirtual = D.getDeclSpec().isVirtualSpecified();
9261  bool hasExplicit = D.getDeclSpec().hasExplicitSpecifier();
9262  isFriend = D.getDeclSpec().isFriendSpecified();
9263  if (isFriend && !isInline && D.isFunctionDefinition()) {
9264  // C++ [class.friend]p5
9265  // A function can be defined in a friend declaration of a
9266  // class . . . . Such a function is implicitly inline.
9267  NewFD->setImplicitlyInline();
9268  }
9269 
9270  // If this is a method defined in an __interface, and is not a constructor
9271  // or an overloaded operator, then set the pure flag (isVirtual will already
9272  // return true).
9273  if (const CXXRecordDecl *Parent =
9274  dyn_cast<CXXRecordDecl>(NewFD->getDeclContext())) {
9275  if (Parent->isInterface() && cast<CXXMethodDecl>(NewFD)->isUserProvided())
9276  NewFD->setPure(true);
9277 
9278  // C++ [class.union]p2
9279  // A union can have member functions, but not virtual functions.
9280  if (isVirtual && Parent->isUnion()) {
9281  Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_in_union);
9282  NewFD->setInvalidDecl();
9283  }
9284  if ((Parent->isClass() || Parent->isStruct()) &&
9285  Parent->hasAttr<SYCLSpecialClassAttr>() &&
9286  NewFD->getKind() == Decl::Kind::CXXMethod && NewFD->getIdentifier() &&
9287  NewFD->getName() == "__init" && D.isFunctionDefinition()) {
9288  if (auto *Def = Parent->getDefinition())
9289  Def->setInitMethod(true);
9290  }
9291  }
9292 
9293  SetNestedNameSpecifier(*this, NewFD, D);
9294  isMemberSpecialization = false;
9295  isFunctionTemplateSpecialization = false;
9296  if (D.isInvalidType())
9297  NewFD->setInvalidDecl();
9298 
9299  // Match up the template parameter lists with the scope specifier, then
9300  // determine whether we have a template or a template specialization.
9301  bool Invalid = false;
9302  TemplateParameterList *TemplateParams =
9303  MatchTemplateParametersToScopeSpecifier(
9305  D.getCXXScopeSpec(),
9307  ? D.getName().TemplateId
9308  : nullptr,
9309  TemplateParamLists, isFriend, isMemberSpecialization,
9310  Invalid);
9311  if (TemplateParams) {
9312  // Check that we can declare a template here.
9313  if (CheckTemplateDeclScope(S, TemplateParams))
9314  NewFD->setInvalidDecl();
9315 
9316  if (TemplateParams->size() > 0) {
9317  // This is a function template
9318 
9319  // A destructor cannot be a template.
9320  if (Name.getNameKind() == DeclarationName::CXXDestructorName) {
9321  Diag(NewFD->getLocation(), diag::err_destructor_template);
9322  NewFD->setInvalidDecl();
9323  }
9324 
9325  // If we're adding a template to a dependent context, we may need to
9326  // rebuilding some of the types used within the template parameter list,
9327  // now that we know what the current instantiation is.
9328  if (DC->isDependentContext()) {
9329  ContextRAII SavedContext(*this, DC);
9330  if (RebuildTemplateParamsInCurrentInstantiation(TemplateParams))
9331  Invalid = true;
9332  }
9333 
9334  FunctionTemplate = FunctionTemplateDecl::Create(Context, DC,
9335  NewFD->getLocation(),
9336  Name, TemplateParams,
9337  NewFD);
9338  FunctionTemplate->setLexicalDeclContext(CurContext);
9339  NewFD->setDescribedFunctionTemplate(FunctionTemplate);
9340 
9341  // For source fidelity, store the other template param lists.
9342  if (TemplateParamLists.size() > 1) {
9343  NewFD->setTemplateParameterListsInfo(Context,
9344  ArrayRef<TemplateParameterList *>(TemplateParamLists)
9345  .drop_back(1));
9346  }
9347  } else {
9348  // This is a function template specialization.
9349  isFunctionTemplateSpecialization = true;
9350  // For source fidelity, store all the template param lists.
9351  if (TemplateParamLists.size() > 0)
9352  NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9353 
9354  // C++0x [temp.expl.spec]p20 forbids "template<> friend void foo(int);".
9355  if (isFriend) {
9356  // We want to remove the "template<>", found here.
9357  SourceRange RemoveRange = TemplateParams->getSourceRange();
9358 
9359  // If we remove the template<> and the name is not a
9360  // template-id, we're actually silently creating a problem:
9361  // the friend declaration will refer to an untemplated decl,
9362  // and clearly the user wants a template specialization. So
9363  // we need to insert '<>' after the name.
9364  SourceLocation InsertLoc;
9366  InsertLoc = D.getName().getSourceRange().getEnd();
9367  InsertLoc = getLocForEndOfToken(InsertLoc);
9368  }
9369 
9370  Diag(D.getIdentifierLoc(), diag::err_template_spec_decl_friend)
9371  << Name << RemoveRange
9372  << FixItHint::CreateRemoval(RemoveRange)
9373  << FixItHint::CreateInsertion(InsertLoc, "<>");
9374  Invalid = true;
9375  }
9376  }
9377  } else {
9378  // Check that we can declare a template here.
9379  if (!TemplateParamLists.empty() && isMemberSpecialization &&
9380  CheckTemplateDeclScope(S, TemplateParamLists.back()))
9381  NewFD->setInvalidDecl();
9382 
9383  // All template param lists were matched against the scope specifier:
9384  // this is NOT (an explicit specialization of) a template.
9385  if (TemplateParamLists.size() > 0)
9386  // For source fidelity, store all the template param lists.
9387  NewFD->setTemplateParameterListsInfo(Context, TemplateParamLists);
9388  }
9389 
9390  if (Invalid) {
9391  NewFD->setInvalidDecl();
9392  if (FunctionTemplate)
9393  FunctionTemplate->setInvalidDecl();
9394  }
9395 
9396  // C++ [dcl.fct.spec]p5:
9397  // The virtual specifier shall only be used in declarations of
9398  // nonstatic class member functions that appear within a
9399  // member-specification of a class declaration; see 10.3.
9400  //
9401  if (isVirtual && !NewFD->isInvalidDecl()) {
9402  if (!isVirtualOkay) {
9404  diag::err_virtual_non_function);
9405  } else if (!CurContext->isRecord()) {
9406  // 'virtual' was specified outside of the class.
9408  diag::err_virtual_out_of_class)
9410  } else if (NewFD->getDescribedFunctionTemplate()) {
9411  // C++ [temp.mem]p3:
9412  // A member function template shall not be virtual.
9414  diag::err_virtual_member_function_template)
9416  } else {
9417  // Okay: Add virtual to the method.
9418  NewFD->setVirtualAsWritten(true);
9419  }
9420 
9421  if (getLangOpts().CPlusPlus14 &&
9422  NewFD->getReturnType()->isUndeducedType())
9423  Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_auto_fn_virtual);
9424  }
9425 
9426  if (getLangOpts().CPlusPlus14 &&
9427  (NewFD->isDependentContext() ||
9428  (isFriend && CurContext->isDependentContext())) &&
9429  NewFD->getReturnType()->isUndeducedType()) {
9430  // If the function template is referenced directly (for instance, as a
9431  // member of the current instantiation), pretend it has a dependent type.
9432  // This is not really justified by the standard, but is the only sane
9433  // thing to do.
9434  // FIXME: For a friend function, we have not marked the function as being
9435  // a friend yet, so 'isDependentContext' on the FD doesn't work.
9436  const FunctionProtoType *FPT =
9437  NewFD->getType()->castAs<FunctionProtoType>();
9438  QualType Result = SubstAutoTypeDependent(FPT->getReturnType());
9439  NewFD->setType(Context.getFunctionType(Result, FPT->getParamTypes(),
9440  FPT->getExtProtoInfo()));
9441  }
9442 
9443  // C++ [dcl.fct.spec]p3:
9444  // The inline specifier shall not appear on a block scope function
9445  // declaration.
9446  if (isInline && !NewFD->isInvalidDecl()) {
9447  if (CurContext->isFunctionOrMethod()) {
9448  // 'inline' is not allowed on block scope function declaration.
9450  diag::err_inline_declaration_block_scope) << Name
9452  }
9453  }
9454 
9455  // C++ [dcl.fct.spec]p6:
9456  // The explicit specifier shall be used only in the declaration of a
9457  // constructor or conversion function within its class definition;
9458  // see 12.3.1 and 12.3.2.
9459  if (hasExplicit && !NewFD->isInvalidDecl() &&
9460  !isa<CXXDeductionGuideDecl>(NewFD)) {
9461  if (!CurContext->isRecord()) {
9462  // 'explicit' was specified outside of the class.
9464  diag::err_explicit_out_of_class)
9466  } else if (!isa<CXXConstructorDecl>(NewFD) &&
9467  !isa<CXXConversionDecl>(NewFD)) {
9468  // 'explicit' was specified on a function that wasn't a constructor
9469  // or conversion function.
9471  diag::err_explicit_non_ctor_or_conv_function)
9473  }
9474  }
9475 
9476  ConstexprSpecKind ConstexprKind = D.getDeclSpec().getConstexprSpecifier();
9477  if (ConstexprKind != ConstexprSpecKind::Unspecified) {
9478  // C++11 [dcl.constexpr]p2: constexpr functions and constexpr constructors
9479  // are implicitly inline.
9480  NewFD->setImplicitlyInline();
9481 
9482  // C++11 [dcl.constexpr]p3: functions declared constexpr are required to
9483  // be either constructors or to return a literal type. Therefore,
9484  // destructors cannot be declared constexpr.
9485  if (isa<CXXDestructorDecl>(NewFD) &&
9486  (!getLangOpts().CPlusPlus20 ||
9487  ConstexprKind == ConstexprSpecKind::Consteval)) {
9488  Diag(D.getDeclSpec().getConstexprSpecLoc(), diag::err_constexpr_dtor)
9489  << static_cast<int>(ConstexprKind);
9490  NewFD->setConstexprKind(getLangOpts().CPlusPlus20
9493  }
9494  // C++20 [dcl.constexpr]p2: An allocation function, or a
9495  // deallocation function shall not be declared with the consteval
9496  // specifier.
9497  if (ConstexprKind == ConstexprSpecKind::Consteval &&
9498  (NewFD->getOverloadedOperator() == OO_New ||
9499  NewFD->getOverloadedOperator() == OO_Array_New ||
9500  NewFD->getOverloadedOperator() == OO_Delete ||
9501  NewFD->getOverloadedOperator() == OO_Array_Delete)) {
9503  diag::err_invalid_consteval_decl_kind)
9504  << NewFD;
9506  }
9507  }
9508 
9509  // If __module_private__ was specified, mark the function accordingly.
9511  if (isFunctionTemplateSpecialization) {
9512  SourceLocation ModulePrivateLoc
9514  Diag(ModulePrivateLoc, diag::err_module_private_specialization)
9515  << 0
9516  << FixItHint::CreateRemoval(ModulePrivateLoc);
9517  } else {
9518  NewFD->setModulePrivate();
9519  if (FunctionTemplate)
9520  FunctionTemplate->setModulePrivate();
9521  }
9522  }
9523 
9524  if (isFriend) {
9525  if (FunctionTemplate) {
9526  FunctionTemplate->setObjectOfFriendDecl();
9527  FunctionTemplate->setAccess(AS_public);
9528  }
9529  NewFD->setObjectOfFriendDecl();
9530  NewFD->setAccess(AS_public);
9531  }
9532 
9533  // If a function is defined as defaulted or deleted, mark it as such now.
9534  // We'll do the relevant checks on defaulted / deleted functions later.
9535  switch (D.getFunctionDefinitionKind()) {
9538  break;
9539 
9541  NewFD->setDefaulted();
9542  break;
9543 
9545  NewFD->setDeletedAsWritten();
9546  break;
9547  }
9548 
9549  if (isa<CXXMethodDecl>(NewFD) && DC == CurContext &&
9550  D.isFunctionDefinition()) {
9551  // C++ [class.mfct]p2:
9552  // A member function may be defined (8.4) in its class definition, in
9553  // which case it is an inline member function (7.1.2)
9554  NewFD->setImplicitlyInline();
9555  }
9556 
9557  if (SC == SC_Static && isa<CXXMethodDecl>(NewFD) &&
9558  !CurContext->isRecord()) {
9559  // C++ [class.static]p1:
9560  // A data or function member of a class may be declared static
9561  // in a class definition, in which case it is a static member of
9562  // the class.
9563 
9564  // Complain about the 'static' specifier if it's on an out-of-line
9565  // member function definition.
9566 
9567  // MSVC permits the use of a 'static' storage specifier on an out-of-line
9568  // member function template declaration and class member template
9569  // declaration (MSVC versions before 2015), warn about this.
9571  ((!getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
9572  cast<CXXRecordDecl>(DC)->getDescribedClassTemplate()) ||
9573  (getLangOpts().MSVCCompat && NewFD->getDescribedFunctionTemplate()))
9574  ? diag::ext_static_out_of_line : diag::err_static_out_of_line)
9576  }
9577 
9578  // C++11 [except.spec]p15:
9579  // A deallocation function with no exception-specification is treated
9580  // as if it were specified with noexcept(true).
9581  const FunctionProtoType *FPT = R->getAs<FunctionProtoType>();
9582  if ((Name.getCXXOverloadedOperator() == OO_Delete ||
9583  Name.getCXXOverloadedOperator() == OO_Array_Delete) &&
9584  getLangOpts().CPlusPlus11 && FPT && !FPT->hasExceptionSpec())
9585  NewFD->setType(Context.getFunctionType(
9586  FPT->getReturnType(), FPT->getParamTypes(),
9588  }
9589 
9590  // Filter out previous declarations that don't match the scope.
9591  FilterLookupForScope(Previous, OriginalDC, S, shouldConsiderLinkage(NewFD),
9592  D.getCXXScopeSpec().isNotEmpty() ||
9593  isMemberSpecialization ||
9594  isFunctionTemplateSpecialization);
9595 
9596  // Handle GNU asm-label extension (encoded as an attribute).
9597  if (Expr *E = (Expr*) D.getAsmLabel()) {
9598  // The parser guarantees this is a string.
9599  StringLiteral *SE = cast<StringLiteral>(E);
9600  NewFD->addAttr(AsmLabelAttr::Create(Context, SE->getString(),
9601  /*IsLiteralLabel=*/true,
9602  SE->getStrTokenLoc(0)));
9603  } else if (!ExtnameUndeclaredIdentifiers.empty()) {
9604  llvm::DenseMap<IdentifierInfo*,AsmLabelAttr*>::iterator I =
9605  ExtnameUndeclaredIdentifiers.find(NewFD->getIdentifier());
9606  if (I != ExtnameUndeclaredIdentifiers.end()) {
9607  if (isDeclExternC(NewFD)) {
9608  NewFD->addAttr(I->second);
9609  ExtnameUndeclaredIdentifiers.erase(I);
9610  } else
9611  Diag(NewFD->getLocation(), diag::warn_redefine_extname_not_applied)
9612  << /*Variable*/0 << NewFD;
9613  }
9614  }
9615 
9616  // Copy the parameter declarations from the declarator D to the function
9617  // declaration NewFD, if they are available. First scavenge them into Params.
9619  unsigned FTIIdx;
9620  if (D.isFunctionDeclarator(FTIIdx)) {
9622 
9623  // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
9624  // function that takes no arguments, not a function that takes a
9625  // single void argument.
9626  // We let through "const void" here because Sema::GetTypeForDeclarator
9627  // already checks for that case.
9628  if (FTIHasNonVoidParameters(FTI) && FTI.Params[0].Param) {
9629  for (unsigned i = 0, e = FTI.NumParams; i != e; ++i) {
9630  ParmVarDecl *Param = cast<ParmVarDecl>(FTI.Params[i].Param);
9631  assert(Param->getDeclContext() != NewFD && "Was set before ?");
9632  Param->setDeclContext(NewFD);
9633  Params.push_back(Param);
9634 
9635  if (Param->isInvalidDecl())
9636  NewFD->setInvalidDecl();
9637  }
9638  }
9639 
9640  if (!getLangOpts().CPlusPlus) {
9641  // In C, find all the tag declarations from the prototype and move them
9642  // into the function DeclContext. Remove them from the surrounding tag
9643  // injection context of the function, which is typically but not always
9644  // the TU.
9645  DeclContext *PrototypeTagContext =
9647  for (NamedDecl *NonParmDecl : FTI.getDeclsInPrototype()) {
9648  auto *TD = dyn_cast<TagDecl>(NonParmDecl);
9649 
9650  // We don't want to reparent enumerators. Look at their parent enum
9651  // instead.
9652  if (!TD) {
9653  if (auto *ECD = dyn_cast<EnumConstantDecl>(NonParmDecl))
9654  TD = cast<EnumDecl>(ECD->getDeclContext());
9655  }
9656  if (!TD)
9657  continue;
9658  DeclContext *TagDC = TD->getLexicalDeclContext();
9659  if (!TagDC->containsDecl(TD))
9660  continue;
9661  TagDC->removeDecl(TD);
9662  TD->setDeclContext(NewFD);
9663  NewFD->addDecl(TD);
9664 
9665  // Preserve the lexical DeclContext if it is not the surrounding tag
9666  // injection context of the FD. In this example, the semantic context of
9667  // E will be f and the lexical context will be S, while both the
9668  // semantic and lexical contexts of S will be f:
9669  // void f(struct S { enum E { a } f; } s);
9670  if (TagDC != PrototypeTagContext)
9671  TD->setLexicalDeclContext(TagDC);
9672  }
9673  }
9674  } else if (const FunctionProtoType *FT = R->getAs<FunctionProtoType>()) {
9675  // When we're declaring a function with a typedef, typeof, etc as in the
9676  // following example, we'll need to synthesize (unnamed)
9677  // parameters for use in the declaration.
9678  //
9679  // @code
9680  // typedef void fn(int);
9681  // fn f;
9682  // @endcode
9683 
9684  // Synthesize a parameter for each argument type.
9685  for (const auto &AI : FT->param_types()) {
9686  ParmVarDecl *Param =
9687  BuildParmVarDeclForTypedef(NewFD, D.getIdentifierLoc(), AI);
9688  Param->setScopeInfo(0, Params.size());
9689  Params.push_back(Param);
9690  }
9691  } else {
9692  assert(R->isFunctionNoProtoType() && NewFD->getNumParams() == 0 &&
9693  "Should not need args for typedef of non-prototype fn");
9694  }
9695 
9696  // Finally, we know we have the right number of parameters, install them.
9697  NewFD->setParams(Params);
9698 
9699  if (D.getDeclSpec().isNoreturnSpecified())
9700  NewFD->addAttr(C11NoReturnAttr::Create(Context,
9703 
9704  // Functions returning a variably modified type violate C99 6.7.5.2p2
9705  // because all functions have linkage.
9706  if (!NewFD->isInvalidDecl() &&
9707  NewFD->getReturnType()->isVariablyModifiedType()) {
9708  Diag(NewFD->getLocation(), diag::err_vm_func_decl);
9709  NewFD->setInvalidDecl();
9710  }
9711 
9712  // Apply an implicit SectionAttr if '#pragma clang section text' is active
9713  if (PragmaClangTextSection.Valid && D.isFunctionDefinition() &&
9714  !NewFD->hasAttr<SectionAttr>())
9715  NewFD->addAttr(PragmaClangTextSectionAttr::CreateImplicit(
9716  Context, PragmaClangTextSection.SectionName,
9717  PragmaClangTextSection.PragmaLocation, AttributeCommonInfo::AS_Pragma));
9718 
9719  // Apply an implicit SectionAttr if #pragma code_seg is active.
9720  if (CodeSegStack.CurrentValue && D.isFunctionDefinition() &&
9721  !NewFD->hasAttr<SectionAttr>()) {
9722  NewFD->addAttr(SectionAttr::CreateImplicit(
9723  Context, CodeSegStack.CurrentValue->getString(),
9724  CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
9725  SectionAttr::Declspec_allocate));
9726  if (UnifySection(CodeSegStack.CurrentValue->getString(),
9729  NewFD))
9730  NewFD->dropAttr<SectionAttr>();
9731  }
9732 
9733  // Apply an implicit CodeSegAttr from class declspec or
9734  // apply an implicit SectionAttr from #pragma code_seg if active.
9735  if (!NewFD->hasAttr<CodeSegAttr>()) {
9736  if (Attr *SAttr = getImplicitCodeSegOrSectionAttrForFunction(NewFD,
9737  D.isFunctionDefinition())) {
9738  NewFD->addAttr(SAttr);
9739  }
9740  }
9741 
9742  // Handle attributes.
9743  ProcessDeclAttributes(S, NewFD, D);
9744 
9745  if (getLangOpts().OpenCL) {
9746  // OpenCL v1.1 s6.5: Using an address space qualifier in a function return
9747  // type declaration will generate a compilation error.
9748  LangAS AddressSpace = NewFD->getReturnType().getAddressSpace();
9749  if (AddressSpace != LangAS::Default) {
9750  Diag(NewFD->getLocation(),
9751  diag::err_opencl_return_value_with_address_space);
9752  NewFD->setInvalidDecl();
9753  }
9754  }
9755 
9756  if (!getLangOpts().CPlusPlus) {
9757  // Perform semantic checking on the function declaration.
9758  if (!NewFD->isInvalidDecl() && NewFD->isMain())
9759  CheckMain(NewFD, D.getDeclSpec());
9760 
9761  if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9762  CheckMSVCRTEntryPoint(NewFD);
9763 
9764  if (!NewFD->isInvalidDecl())
9765  D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9766  isMemberSpecialization));
9767  else if (!Previous.empty())
9768  // Recover gracefully from an invalid redeclaration.
9769  D.setRedeclaration(true);
9770  assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9771  Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9772  "previous declaration set still overloaded");
9773 
9774  // Diagnose no-prototype function declarations with calling conventions that
9775  // don't support variadic calls. Only do this in C and do it after merging
9776  // possibly prototyped redeclarations.
9777  const FunctionType *FT = NewFD->getType()->castAs<FunctionType>();
9778  if (isa<FunctionNoProtoType>(FT) && !D.isFunctionDefinition()) {
9779  CallingConv CC = FT->getExtInfo().getCC();
9780  if (!supportsVariadicCall(CC)) {
9781  // Windows system headers sometimes accidentally use stdcall without
9782  // (void) parameters, so we relax this to a warning.
9783  int DiagID =
9784  CC == CC_X86StdCall ? diag::warn_cconv_knr : diag::err_cconv_knr;
9785  Diag(NewFD->getLocation(), DiagID)
9787  }
9788  }
9789 
9792  checkNonTrivialCUnion(NewFD->getReturnType(),
9794  NTCUC_FunctionReturn, NTCUK_Destruct|NTCUK_Copy);
9795  } else {
9796  // C++11 [replacement.functions]p3:
9797  // The program's definitions shall not be specified as inline.
9798  //
9799  // N.B. We diagnose declarations instead of definitions per LWG issue 2340.
9800  //
9801  // Suppress the diagnostic if the function is __attribute__((used)), since
9802  // that forces an external definition to be emitted.
9803  if (D.getDeclSpec().isInlineSpecified() &&
9805  !NewFD->hasAttr<UsedAttr>())
9807  diag::ext_operator_new_delete_declared_inline)
9808  << NewFD->getDeclName();
9809 
9810  // If the declarator is a template-id, translate the parser's template
9811  // argument list into our AST format.
9813  TemplateIdAnnotation *TemplateId = D.getName().TemplateId;
9814  TemplateArgs.setLAngleLoc(TemplateId->LAngleLoc);
9815  TemplateArgs.setRAngleLoc(TemplateId->RAngleLoc);
9816  ASTTemplateArgsPtr TemplateArgsPtr(TemplateId->getTemplateArgs(),
9817  TemplateId->NumArgs);
9818  translateTemplateArguments(TemplateArgsPtr,
9819  TemplateArgs);
9820 
9821  HasExplicitTemplateArgs = true;
9822 
9823  if (NewFD->isInvalidDecl()) {
9824  HasExplicitTemplateArgs = false;
9825  } else if (FunctionTemplate) {
9826  // Function template with explicit template arguments.
9827  Diag(D.getIdentifierLoc(), diag::err_function_template_partial_spec)
9828  << SourceRange(TemplateId->LAngleLoc, TemplateId->RAngleLoc);
9829 
9830  HasExplicitTemplateArgs = false;
9831  } else {
9832  assert((isFunctionTemplateSpecialization ||
9833  D.getDeclSpec().isFriendSpecified()) &&
9834  "should have a 'template<>' for this decl");
9835  // "friend void foo<>(int);" is an implicit specialization decl.
9836  isFunctionTemplateSpecialization = true;
9837  }
9838  } else if (isFriend && isFunctionTemplateSpecialization) {
9839  // This combination is only possible in a recovery case; the user
9840  // wrote something like:
9841  // template <> friend void foo(int);
9842  // which we're recovering from as if the user had written:
9843  // friend void foo<>(int);
9844  // Go ahead and fake up a template id.
9845  HasExplicitTemplateArgs = true;
9846  TemplateArgs.setLAngleLoc(D.getIdentifierLoc());
9847  TemplateArgs.setRAngleLoc(D.getIdentifierLoc());
9848  }
9849 
9850  // We do not add HD attributes to specializations here because
9851  // they may have different constexpr-ness compared to their
9852  // templates and, after maybeAddCUDAHostDeviceAttrs() is applied,
9853  // may end up with different effective targets. Instead, a
9854  // specialization inherits its target attributes from its template
9855  // in the CheckFunctionTemplateSpecialization() call below.
9856  if (getLangOpts().CUDA && !isFunctionTemplateSpecialization)
9857  maybeAddCUDAHostDeviceAttrs(NewFD, Previous);
9858 
9859  // If it's a friend (and only if it's a friend), it's possible
9860  // that either the specialized function type or the specialized
9861  // template is dependent, and therefore matching will fail. In
9862  // this case, don't check the specialization yet.
9863  if (isFunctionTemplateSpecialization && isFriend &&
9864  (NewFD->getType()->isDependentType() || DC->isDependentContext() ||
9866  TemplateArgs.arguments()))) {
9867  assert(HasExplicitTemplateArgs &&
9868  "friend function specialization without template args");
9869  if (CheckDependentFunctionTemplateSpecialization(NewFD, TemplateArgs,
9870  Previous))
9871  NewFD->setInvalidDecl();
9872  } else if (isFunctionTemplateSpecialization) {
9873  if (CurContext->isDependentContext() && CurContext->isRecord()
9874  && !isFriend) {
9875  isDependentClassScopeExplicitSpecialization = true;
9876  } else if (!NewFD->isInvalidDecl() &&
9877  CheckFunctionTemplateSpecialization(
9878  NewFD, (HasExplicitTemplateArgs ? &TemplateArgs : nullptr),
9879  Previous))
9880  NewFD->setInvalidDecl();
9881 
9882  // C++ [dcl.stc]p1:
9883  // A storage-class-specifier shall not be specified in an explicit
9884  // specialization (14.7.3)
9887  if (Info && SC != SC_None) {
9888  if (SC != Info->getTemplate()->getTemplatedDecl()->getStorageClass())
9889  Diag(NewFD->getLocation(),
9890  diag::err_explicit_specialization_inconsistent_storage_class)
9891  << SC
9894 
9895  else
9896  Diag(NewFD->getLocation(),
9897  diag::ext_explicit_specialization_storage_class)
9900  }
9901  } else if (isMemberSpecialization && isa<CXXMethodDecl>(NewFD)) {
9902  if (CheckMemberSpecialization(NewFD, Previous))
9903  NewFD->setInvalidDecl();
9904  }
9905 
9906  // Perform semantic checking on the function declaration.
9907  if (!isDependentClassScopeExplicitSpecialization) {
9908  if (!NewFD->isInvalidDecl() && NewFD->isMain())
9909  CheckMain(NewFD, D.getDeclSpec());
9910 
9911  if (!NewFD->isInvalidDecl() && NewFD->isMSVCRTEntryPoint())
9912  CheckMSVCRTEntryPoint(NewFD);
9913 
9914  if (!NewFD->isInvalidDecl())
9915  D.setRedeclaration(CheckFunctionDeclaration(S, NewFD, Previous,
9916  isMemberSpecialization));
9917  else if (!Previous.empty())
9918  // Recover gracefully from an invalid redeclaration.
9919  D.setRedeclaration(true);
9920  }
9921 
9922  assert((NewFD->isInvalidDecl() || !D.isRedeclaration() ||
9923  Previous.getResultKind() != LookupResult::FoundOverloaded) &&
9924  "previous declaration set still overloaded");
9925 
9926  NamedDecl *PrincipalDecl = (FunctionTemplate
9927  ? cast<NamedDecl>(FunctionTemplate)
9928  : NewFD);
9929 
9930  if (isFriend && NewFD->getPreviousDecl()) {
9931  AccessSpecifier Access = AS_public;
9932  if (!NewFD->isInvalidDecl())
9933  Access = NewFD->getPreviousDecl()->getAccess();
9934 
9935  NewFD->setAccess(Access);
9936  if (FunctionTemplate) FunctionTemplate->setAccess(Access);
9937  }
9938 
9939  if (NewFD->isOverloadedOperator() && !DC->isRecord() &&
9941  PrincipalDecl->setNonMemberOperator();
9942 
9943  // If we have a function template, check the template parameter
9944  // list. This will check and merge default template arguments.
9945  if (FunctionTemplate) {
9946  FunctionTemplateDecl *PrevTemplate =
9947  FunctionTemplate->getPreviousDecl();
9948  CheckTemplateParameterList(FunctionTemplate->getTemplateParameters(),
9949  PrevTemplate ? PrevTemplate->getTemplateParameters()
9950  : nullptr,
9952  ? (D.isFunctionDefinition()
9953  ? TPC_FriendFunctionTemplateDefinition
9954  : TPC_FriendFunctionTemplate)
9955  : (D.getCXXScopeSpec().isSet() &&
9956  DC && DC->isRecord() &&
9957  DC->isDependentContext())
9958  ? TPC_ClassTemplateMember
9959  : TPC_FunctionTemplate);
9960  }
9961 
9962  if (NewFD->isInvalidDecl()) {
9963  // Ignore all the rest of this.
9964  } else if (!D.isRedeclaration()) {
9965  struct ActOnFDArgs ExtraArgs = { S, D, TemplateParamLists,
9966  AddToScope };
9967  // Fake up an access specifier if it's supposed to be a class member.
9968  if (isa<CXXRecordDecl>(NewFD->getDeclContext()))
9969  NewFD->setAccess(AS_public);
9970 
9971  // Qualified decls generally require a previous declaration.
9972  if (D.getCXXScopeSpec().isSet()) {
9973  // ...with the major exception of templated-scope or
9974  // dependent-scope friend declarations.
9975 
9976  // TODO: we currently also suppress this check in dependent
9977  // contexts because (1) the parameter depth will be off when
9978  // matching friend templates and (2) we might actually be
9979  // selecting a friend based on a dependent factor. But there
9980  // are situations where these conditions don't apply and we
9981  // can actually do this check immediately.
9982  //
9983  // Unless the scope is dependent, it's always an error if qualified
9984  // redeclaration lookup found nothing at all. Diagnose that now;
9985  // nothing will diagnose that error later.
9986  if (isFriend &&
9988  (!Previous.empty() && CurContext->isDependentContext()))) {
9989  // ignore these
9990  } else if (NewFD->isCPUDispatchMultiVersion() ||
9991  NewFD->isCPUSpecificMultiVersion()) {
9992  // ignore this, we allow the redeclaration behavior here to create new
9993  // versions of the function.
9994  } else {
9995  // The user tried to provide an out-of-line definition for a
9996  // function that is a member of a class or namespace, but there
9997  // was no such member function declared (C++ [class.mfct]p2,
9998  // C++ [namespace.memdef]p2). For example:
9999  //
10000  // class X {
10001  // void f() const;
10002  // };
10003  //
10004  // void X::f() { } // ill-formed
10005  //
10006  // Complain about this problem, and attempt to suggest close
10007  // matches (e.g., those that differ only in cv-qualifiers and
10008  // whether the parameter types are references).
10009 
10011  *this, Previous, NewFD, ExtraArgs, false, nullptr)) {
10012  AddToScope = ExtraArgs.AddToScope;
10013  return Result;
10014  }
10015  }
10016 
10017  // Unqualified local friend declarations are required to resolve
10018  // to something.
10019  } else if (isFriend && cast<CXXRecordDecl>(CurContext)->isLocalClass()) {
10021  *this, Previous, NewFD, ExtraArgs, true, S)) {
10022  AddToScope = ExtraArgs.AddToScope;
10023  return Result;
10024  }
10025  }
10026  } else if (!D.isFunctionDefinition() &&
10027  isa<CXXMethodDecl>(NewFD) && NewFD->isOutOfLine() &&
10028  !isFriend && !isFunctionTemplateSpecialization &&
10029  !isMemberSpecialization) {
10030  // An out-of-line member function declaration must also be a
10031  // definition (C++ [class.mfct]p2).
10032  // Note that this is not the case for explicit specializations of
10033  // function templates or member functions of class templates, per
10034  // C++ [temp.expl.spec]p2. We also allow these declarations as an
10035  // extension for compatibility with old SWIG code which likes to
10036  // generate them.
10037  Diag(NewFD->getLocation(), diag::ext_out_of_line_declaration)
10038  << D.getCXXScopeSpec().getRange();
10039  }
10040  }
10041 
10042  // If this is the first declaration of a library builtin function, add
10043  // attributes as appropriate.
10044  if (!D.isRedeclaration() &&
10046  if (IdentifierInfo *II = Previous.getLookupName().getAsIdentifierInfo()) {
10047  if (unsigned BuiltinID = II->getBuiltinID()) {
10048  if (NewFD->getLanguageLinkage() == CLanguageLinkage) {
10049  // Validate the type matches unless this builtin is specified as
10050  // matching regardless of its declared type.
10051  if (Context.BuiltinInfo.allowTypeMismatch(BuiltinID)) {
10052  NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10053  } else {
10055  LookupNecessaryTypesForBuiltin(S, BuiltinID);
10056  QualType BuiltinType = Context.GetBuiltinType(BuiltinID, Error);
10057 
10058  if (!Error && !BuiltinType.isNull() &&
10060  NewFD->getType(), BuiltinType))
10061  NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10062  }
10063  } else if (BuiltinID == Builtin::BI__GetExceptionInfo &&
10064  Context.getTargetInfo().getCXXABI().isMicrosoft()) {
10065  // FIXME: We should consider this a builtin only in the std namespace.
10066  NewFD->addAttr(BuiltinAttr::CreateImplicit(Context, BuiltinID));
10067  }
10068  }
10069  }
10070  }
10071 
10072  ProcessPragmaWeak(S, NewFD);
10073  checkAttributesAfterMerging(*this, *NewFD);
10074 
10075  AddKnownFunctionAttributes(NewFD);
10076 
10077  if (NewFD->hasAttr<OverloadableAttr>() &&
10078  !NewFD->getType()->getAs<FunctionProtoType>()) {
10079  Diag(NewFD->getLocation(),
10080  diag::err_attribute_overloadable_no_prototype)
10081  << NewFD;
10082 
10083  // Turn this into a variadic function with no parameters.
10084  const auto *FT = NewFD->getType()->castAs<FunctionType>();
10086  Context.getDefaultCallingConvention(true, false));
10087  EPI.Variadic = true;
10088  EPI.ExtInfo = FT->getExtInfo();
10089 
10090  QualType R = Context.getFunctionType(FT->getReturnType(), None, EPI);
10091  NewFD->setType(R);
10092  }
10093 
10094  // If there's a #pragma GCC visibility in scope, and this isn't a class
10095  // member, set the visibility of this function.
10096  if (!DC->isRecord() && NewFD->isExternallyVisible())
10097  AddPushedVisibilityAttribute(NewFD);
10098 
10099  // If there's a #pragma clang arc_cf_code_audited in scope, consider
10100  // marking the function.
10101  AddCFAuditedAttribute(NewFD);
10102 
10103  // If this is a function definition, check if we have to apply optnone due to
10104  // a pragma.
10105  if(D.isFunctionDefinition())
10106  AddRangeBasedOptnone(NewFD);
10107 
10108  // If this is the first declaration of an extern C variable, update
10109  // the map of such variables.
10110  if (NewFD->isFirstDecl() && !NewFD->isInvalidDecl() &&
10111  isIncompleteDeclExternC(*this, NewFD))
10112  RegisterLocallyScopedExternCDecl(NewFD, S);
10113 
10114  // Set this FunctionDecl's range up to the right paren.
10115  NewFD->setRangeEnd(D.getSourceRange().getEnd());
10116 
10117  if (D.isRedeclaration() && !Previous.empty()) {
10118  NamedDecl *Prev = Previous.getRepresentativeDecl();
10119  checkDLLAttributeRedeclaration(*this, Prev, NewFD,
10120  isMemberSpecialization ||
10121  isFunctionTemplateSpecialization,
10122  D.isFunctionDefinition());
10123  }
10124 
10125  if (getLangOpts().CUDA) {
10126  IdentifierInfo *II = NewFD->getIdentifier();
10127  if (II && II->isStr(getCudaConfigureFuncName()) &&
10128  !NewFD->isInvalidDecl() &&
10130  if (!R->castAs<FunctionType>()->getReturnType()->isScalarType())
10131  Diag(NewFD->getLocation(), diag::err_config_scalar_return)
10132  << getCudaConfigureFuncName();
10133  Context.setcudaConfigureCallDecl(NewFD);
10134  }
10135 
10136  // Variadic functions, other than a *declaration* of printf, are not allowed
10137  // in device-side CUDA code, unless someone passed
10138  // -fcuda-allow-variadic-functions.
10139  if (!getLangOpts().CUDAAllowVariadicFunctions && NewFD->isVariadic() &&
10140  (NewFD->hasAttr<CUDADeviceAttr>() ||
10141  NewFD->hasAttr<CUDAGlobalAttr>()) &&
10142  !(II && II->isStr("printf") && NewFD->isExternC() &&
10143  !D.isFunctionDefinition())) {
10144  Diag(NewFD->getLocation(), diag::err_variadic_device_fn);
10145  }
10146  }
10147 
10148  MarkUnusedFileScopedDecl(NewFD);
10149 
10150 
10151 
10152  if (getLangOpts().OpenCL && NewFD->hasAttr<OpenCLKernelAttr>()) {
10153  // OpenCL v1.2 s6.8 static is invalid for kernel functions.
10154  if (SC == SC_Static) {
10155  Diag(D.getIdentifierLoc(), diag::err_static_kernel);
10156  D.setInvalidType();
10157  }
10158 
10159  // OpenCL v1.2, s6.9 -- Kernels can only have return type void.
10160  if (!NewFD->getReturnType()->isVoidType()) {
10161  SourceRange RTRange = NewFD->getReturnTypeSourceRange();
10162  Diag(D.getIdentifierLoc(), diag::err_expected_kernel_void_return_type)
10163  << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "void")
10164  : FixItHint());
10165  D.setInvalidType();
10166  }
10167 
10169  for (auto Param : NewFD->parameters())
10170  checkIsValidOpenCLKernelParameter(*this, D, Param, ValidTypes);
10171 
10172  if (getLangOpts().OpenCLCPlusPlus) {
10173  if (DC->isRecord()) {
10174  Diag(D.getIdentifierLoc(), diag::err_method_kernel);
10175  D.setInvalidType();
10176  }
10177  if (FunctionTemplate) {
10178  Diag(D.getIdentifierLoc(), diag::err_template_kernel);
10179  D.setInvalidType();
10180  }
10181  }
10182  }
10183 
10184  if (getLangOpts().CPlusPlus) {
10185  if (FunctionTemplate) {
10186  if (NewFD->isInvalidDecl())
10187  FunctionTemplate->setInvalidDecl();
10188  return FunctionTemplate;
10189  }
10190 
10191  if (isMemberSpecialization && !NewFD->isInvalidDecl())
10192  CompleteMemberSpecialization(NewFD, Previous);
10193  }
10194 
10195  for (const ParmVarDecl *Param : NewFD->parameters()) {
10196  QualType PT = Param->getType();
10197 
10198  if (const PipeType *PipeTy = PT->getAs<PipeType>()) {
10199  QualType ElemTy = PipeTy->getElementType();
10200  if (ElemTy->isReferenceType() || ElemTy->isPointerType()) {
10201  Diag(Param->getTypeSpecStartLoc(), diag::err_reference_pipe_type );
10202  D.setInvalidType();
10203  }
10204  }
10205  }
10206 
10207  // Here we have an function template explicit specialization at class scope.
10208  // The actual specialization will be postponed to template instatiation
10209  // time via the ClassScopeFunctionSpecializationDecl node.
10210  if (isDependentClassScopeExplicitSpecialization) {
10213  Context, CurContext, NewFD->getLocation(),
10214  cast<CXXMethodDecl>(NewFD),
10215  HasExplicitTemplateArgs, TemplateArgs);
10216  CurContext->addDecl(NewSpec);
10217  AddToScope = false;
10218  }
10219 
10220  // Diagnose availability attributes. Availability cannot be used on functions
10221  // that are run during load/unload.
10222  if (const auto *attr = NewFD->getAttr<AvailabilityAttr>()) {
10223  if (NewFD->hasAttr<ConstructorAttr>()) {
10224  Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10225  << 1;
10226  NewFD->dropAttr<AvailabilityAttr>();
10227  }
10228  if (NewFD->hasAttr<DestructorAttr>()) {
10229  Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
10230  << 2;
10231  NewFD->dropAttr<AvailabilityAttr>();
10232  }
10233  }
10234 
10235  // Diagnose no_builtin attribute on function declaration that are not a
10236  // definition.
10237  // FIXME: We should really be doing this in
10238  // SemaDeclAttr.cpp::handleNoBuiltinAttr, unfortunately we only have access to
10239  // the FunctionDecl and at this point of the code
10240  // FunctionDecl::isThisDeclarationADefinition() which always returns `false`
10241  // because Sema::ActOnStartOfFunctionDef has not been called yet.
10242  if (const auto *NBA = NewFD->getAttr<NoBuiltinAttr>())
10243  switch (D.getFunctionDefinitionKind()) {
10246  Diag(NBA->getLocation(),
10247  diag::err_attribute_no_builtin_on_defaulted_deleted_function)
10248  << NBA->getSpelling();
10249  break;
10251  Diag(NBA->getLocation(), diag::err_attribute_no_builtin_on_non_definition)
10252  << NBA->getSpelling();
10253  break;
10255  break;
10256  }
10257 
10258  return NewFD;
10259 }
10260 
10261 /// Return a CodeSegAttr from a containing class. The Microsoft docs say
10262 /// when __declspec(code_seg) "is applied to a class, all member functions of
10263 /// the class and nested classes -- this includes compiler-generated special
10264 /// member functions -- are put in the specified segment."
10265 /// The actual behavior is a little more complicated. The Microsoft compiler
10266 /// won't check outer classes if there is an active value from #pragma code_seg.
10267 /// The CodeSeg is always applied from the direct parent but only from outer
10268 /// classes when the #pragma code_seg stack is empty. See:
10269 /// https://reviews.llvm.org/D22931, the Microsoft feedback page is no longer
10270 /// available since MS has removed the page.
10272  const auto *Method = dyn_cast<CXXMethodDecl>(FD);
10273  if (!Method)
10274  return nullptr;
10275  const CXXRecordDecl *Parent = Method->getParent();
10276  if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10277  Attr *NewAttr = SAttr->clone(S.getASTContext());
10278  NewAttr->setImplicit(true);
10279  return NewAttr;
10280  }
10281 
10282  // The Microsoft compiler won't check outer classes for the CodeSeg
10283  // when the #pragma code_seg stack is active.
10284  if (S.CodeSegStack.CurrentValue)
10285  return nullptr;
10286 
10287  while ((Parent = dyn_cast<CXXRecordDecl>(Parent->getParent()))) {
10288  if (const auto *SAttr = Parent->getAttr<CodeSegAttr>()) {
10289  Attr *NewAttr = SAttr->clone(S.getASTContext());
10290  NewAttr->setImplicit(true);
10291  return NewAttr;
10292  }
10293  }
10294  return nullptr;
10295 }
10296 
10297 /// Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a
10298 /// containing class. Otherwise it will return implicit SectionAttr if the
10299 /// function is a definition and there is an active value on CodeSegStack
10300 /// (from the current #pragma code-seg value).
10301 ///
10302 /// \param FD Function being declared.
10303 /// \param IsDefinition Whether it is a definition or just a declarartion.
10304 /// \returns A CodeSegAttr or SectionAttr to apply to the function or
10305 /// nullptr if no attribute should be added.
10307  bool IsDefinition) {
10308  if (Attr *A = getImplicitCodeSegAttrFromClass(*this, FD))
10309  return A;
10310  if (!FD->hasAttr<SectionAttr>() && IsDefinition &&
10311  CodeSegStack.CurrentValue)
10312  return SectionAttr::CreateImplicit(
10313  getASTContext(), CodeSegStack.CurrentValue->getString(),
10314  CodeSegStack.CurrentPragmaLocation, AttributeCommonInfo::AS_Pragma,
10315  SectionAttr::Declspec_allocate);
10316  return nullptr;
10317 }
10318 
10319 /// Determines if we can perform a correct type check for \p D as a
10320 /// redeclaration of \p PrevDecl. If not, we can generally still perform a
10321 /// best-effort check.
10322 ///
10323 /// \param NewD The new declaration.
10324 /// \param OldD The old declaration.
10325 /// \param NewT The portion of the type of the new declaration to check.
10326 /// \param OldT The portion of the type of the old declaration to check.
10328  QualType NewT, QualType OldT) {
10329  if (!NewD->getLexicalDeclContext()->isDependentContext())
10330  return true;
10331 
10332  // For dependently-typed local extern declarations and friends, we can't
10333  // perform a correct type check in general until instantiation:
10334  //
10335  // int f();
10336  // template<typename T> void g() { T f(); }
10337  //
10338  // (valid if g() is only instantiated with T = int).
10339  if (NewT->isDependentType() &&
10340  (NewD->isLocalExternDecl() || NewD->getFriendObjectKind()))
10341  return false;
10342 
10343  // Similarly, if the previous declaration was a dependent local extern
10344  // declaration, we don't really know its type yet.
10345  if (OldT->isDependentType() && OldD->isLocalExternDecl())
10346  return false;
10347 
10348  return true;
10349 }
10350 
10351 /// Checks if the new declaration declared in dependent context must be
10352 /// put in the same redeclaration chain as the specified declaration.
10353 ///
10354 /// \param D Declaration that is checked.
10355 /// \param PrevDecl Previous declaration found with proper lookup method for the
10356 /// same declaration name.
10357 /// \returns True if D must be added to the redeclaration chain which PrevDecl
10358 /// belongs to.
10359 ///
10362  return true;
10363 
10364  // Don't chain dependent friend function definitions until instantiation, to
10365  // permit cases like
10366  //
10367  // void func();
10368  // template<typename T> class C1 { friend void func() {} };
10369  // template<typename T> class C2 { friend void func() {} };
10370  //
10371  // ... which is valid if only one of C1 and C2 is ever instantiated.
10372  //
10373  // FIXME: This need only apply to function definitions. For now, we proxy
10374  // this by checking for a file-scope function. We do not want this to apply
10375  // to friend declarations nominating member functions, because that gets in
10376  // the way of access checks.
10377  if (D->getFriendObjectKind() && D->getDeclContext()->isFileContext())
10378  return false;
10379 
10380  auto *VD = dyn_cast<ValueDecl>(D);
10381  auto *PrevVD = dyn_cast<ValueDecl>(PrevDecl);
10382  return !VD || !PrevVD ||
10383  canFullyTypeCheckRedeclaration(VD, PrevVD, VD->getType(),
10384  PrevVD->getType());
10385 }
10386 
10387 /// Check the target attribute of the function for MultiVersion
10388 /// validity.
10389 ///
10390 /// Returns true if there was an error, false otherwise.
10391 static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD) {
10392  const auto *TA = FD->getAttr<TargetAttr>();
10393  assert(TA && "MultiVersion Candidate requires a target attribute");
10394  ParsedTargetAttr ParseInfo = TA->parse();
10396  enum ErrType { Feature = 0, Architecture = 1 };
10397 
10398  if (!ParseInfo.Architecture.empty() &&
10399  !TargetInfo.validateCpuIs(ParseInfo.Architecture)) {
10400  S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10401  << Architecture << ParseInfo.Architecture;
10402  return true;
10403  }
10404 
10405  for (const auto &Feat : ParseInfo.Features) {
10406  auto BareFeat = StringRef{Feat}.substr(1);
10407  if (Feat[0] == '-') {
10408  S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10409  << Feature << ("no-" + BareFeat).str();
10410  return true;
10411  }
10412 
10413  if (!TargetInfo.validateCpuSupports(BareFeat) ||
10414  !TargetInfo.isValidFeatureName(BareFeat)) {
10415  S.Diag(FD->getLocation(), diag::err_bad_multiversion_option)
10416  << Feature << BareFeat;
10417  return true;
10418  }
10419  }
10420  return false;
10421 }
10422 
10423 // Provide a white-list of attributes that are allowed to be combined with
10424 // multiversion functions.
10426  MultiVersionKind MVKind) {
10427  // Note: this list/diagnosis must match the list in
10428  // checkMultiversionAttributesAllSame.
10429  switch (Kind) {
10430  default:
10431  return false;
10432  case attr::Used:
10433  return MVKind == MultiVersionKind::Target;
10434  case attr::NonNull:
10435  case attr::NoThrow:
10436  return true;
10437  }
10438 }
10439 
10441  const FunctionDecl *FD,
10442  const FunctionDecl *CausedFD,
10443  MultiVersionKind MVKind) {
10444  const auto Diagnose = [FD, CausedFD, MVKind](Sema &S, const Attr *A) {
10445  S.Diag(FD->getLocation(), diag::err_multiversion_disallowed_other_attr)
10446  << static_cast<unsigned>(MVKind) << A;
10447  if (CausedFD)
10448  S.Diag(CausedFD->getLocation(), diag::note_multiversioning_caused_here);
10449  return true;
10450  };
10451 
10452  for (const Attr *A : FD->attrs()) {
10453  switch (A->getKind()) {
10454  case attr::CPUDispatch:
10455  case attr::CPUSpecific:
10456  if (MVKind != MultiVersionKind::CPUDispatch &&
10458  return Diagnose(S, A);
10459  break;
10460  case attr::Target:
10461  if (MVKind != MultiVersionKind::Target)
10462  return Diagnose(S, A);
10463  break;
10464  case attr::TargetClones:
10465  if (MVKind != MultiVersionKind::TargetClones)
10466  return Diagnose(S, A);
10467  break;
10468  default:
10469  if (!AttrCompatibleWithMultiVersion(A->getKind(), MVKind))
10470  return Diagnose(S, A);
10471  break;
10472  }
10473  }
10474  return false;
10475 }
10476 
10478  const FunctionDecl *OldFD, const FunctionDecl *NewFD,
10479  const PartialDiagnostic &NoProtoDiagID,
10480  const PartialDiagnosticAt &NoteCausedDiagIDAt,
10481  const PartialDiagnosticAt &NoSupportDiagIDAt,
10482  const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported,
10483  bool ConstexprSupported, bool CLinkageMayDiffer) {
10484  enum DoesntSupport {
10485  FuncTemplates = 0,
10486  VirtFuncs = 1,
10487  DeducedReturn = 2,
10488  Constructors = 3,
10489  Destructors = 4,
10490  DeletedFuncs = 5,
10491  DefaultedFuncs = 6,
10492  ConstexprFuncs = 7,
10493  ConstevalFuncs = 8,
10494  Lambda = 9,
10495  };
10496  enum Different {
10497  CallingConv = 0,
10498  ReturnType = 1,
10499  ConstexprSpec = 2,
10500  InlineSpec = 3,
10501  Linkage = 4,
10502  LanguageLinkage = 5,
10503  };
10504 
10505  if (NoProtoDiagID.getDiagID() != 0 && OldFD &&
10506  !OldFD->getType()->getAs<FunctionProtoType>()) {
10507  Diag(OldFD->getLocation(), NoProtoDiagID);
10508  Diag(NoteCausedDiagIDAt.first, NoteCausedDiagIDAt.second);
10509  return true;
10510  }
10511 
10512  if (NoProtoDiagID.getDiagID() != 0 &&
10513  !NewFD->getType()->getAs<FunctionProtoType>())
10514  return Diag(NewFD->getLocation(), NoProtoDiagID);
10515 
10516  if (!TemplatesSupported &&
10518  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10519  << FuncTemplates;
10520 
10521  if (const auto *NewCXXFD = dyn_cast<CXXMethodDecl>(NewFD)) {
10522  if (NewCXXFD->isVirtual())
10523  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10524  << VirtFuncs;
10525 
10526  if (isa<CXXConstructorDecl>(NewCXXFD))
10527  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10528  << Constructors;
10529 
10530  if (isa<CXXDestructorDecl>(NewCXXFD))
10531  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10532  << Destructors;
10533  }
10534 
10535  if (NewFD->isDeleted())
10536  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10537  << DeletedFuncs;
10538 
10539  if (NewFD->isDefaulted())
10540  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10541  << DefaultedFuncs;
10542 
10543  if (!ConstexprSupported && NewFD->isConstexpr())
10544  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10545  << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
10546 
10547  QualType NewQType = Context.getCanonicalType(NewFD->getType());
10548  const auto *NewType = cast<FunctionType>(NewQType);
10549  QualType NewReturnType = NewType->getReturnType();
10550 
10551  if (NewReturnType->isUndeducedType())
10552  return Diag(NoSupportDiagIDAt.first, NoSupportDiagIDAt.second)
10553  << DeducedReturn;
10554 
10555  // Ensure the return type is identical.
10556  if (OldFD) {
10557  QualType OldQType = Context.getCanonicalType(OldFD->getType());
10558  const auto *OldType = cast<FunctionType>(OldQType);
10559  FunctionType::ExtInfo OldTypeInfo = OldType->getExtInfo();
10560  FunctionType::ExtInfo NewTypeInfo = NewType->getExtInfo();
10561 
10562  if (OldTypeInfo.getCC() != NewTypeInfo.getCC())
10563  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << CallingConv;
10564 
10565  QualType OldReturnType = OldType->getReturnType();
10566 
10567  if (OldReturnType != NewReturnType)
10568  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ReturnType;
10569 
10570  if (OldFD->getConstexprKind() != NewFD->getConstexprKind())
10571  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << ConstexprSpec;
10572 
10573  if (OldFD->isInlineSpecified() != NewFD->isInlineSpecified())
10574  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << InlineSpec;
10575 
10576  if (OldFD->getFormalLinkage() != NewFD->getFormalLinkage())
10577  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << Linkage;
10578 
10579  if (!CLinkageMayDiffer && OldFD->isExternC() != NewFD->isExternC())
10580  return Diag(DiffDiagIDAt.first, DiffDiagIDAt.second) << LanguageLinkage;
10581 
10582  if (CheckEquivalentExceptionSpec(
10583  OldFD->getType()->getAs<FunctionProtoType>(), OldFD->getLocation(),
10584  NewFD->getType()->getAs<FunctionProtoType>(), NewFD->getLocation()))
10585  return true;
10586  }
10587  return false;
10588 }
10589 
10591  const FunctionDecl *NewFD,
10592  bool CausesMV,
10593  MultiVersionKind MVKind) {
10595  S.Diag(NewFD->getLocation(), diag::err_multiversion_not_supported);
10596  if (OldFD)
10597  S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10598  return true;
10599  }
10600 
10601  bool IsCPUSpecificCPUDispatchMVKind =
10602  MVKind == MultiVersionKind::CPUDispatch ||
10604 
10605  if (CausesMV && OldFD &&
10606  checkNonMultiVersionCompatAttributes(S, OldFD, NewFD, MVKind))
10607  return true;
10608 
10609  if (checkNonMultiVersionCompatAttributes(S, NewFD, nullptr, MVKind))
10610  return true;
10611 
10612  // Only allow transition to MultiVersion if it hasn't been used.
10613  if (OldFD && CausesMV && OldFD->isUsed(false))
10614  return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10615 
10617  OldFD, NewFD, S.PDiag(diag::err_multiversion_noproto),
10619  S.PDiag(diag::note_multiversioning_caused_here)),
10621  S.PDiag(diag::err_multiversion_doesnt_support)
10622  << static_cast<unsigned>(MVKind)),
10624  S.PDiag(diag::err_multiversion_diff)),
10625  /*TemplatesSupported=*/false,
10626  /*ConstexprSupported=*/!IsCPUSpecificCPUDispatchMVKind,
10627  /*CLinkageMayDiffer=*/false);
10628 }
10629 
10630 /// Check the validity of a multiversion function declaration that is the
10631 /// first of its kind. Also sets the multiversion'ness' of the function itself.
10632 ///
10633 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10634 ///
10635 /// Returns true if there was an error, false otherwise.
10637  MultiVersionKind MVKind,
10638  const TargetAttr *TA) {
10639  assert(MVKind != MultiVersionKind::None &&
10640  "Function lacks multiversion attribute");
10641 
10642  // Target only causes MV if it is default, otherwise this is a normal
10643  // function.
10644  if (MVKind == MultiVersionKind::Target && !TA->isDefaultVersion())
10645  return false;
10646 
10647  if (MVKind == MultiVersionKind::Target && CheckMultiVersionValue(S, FD)) {
10648  FD->setInvalidDecl();
10649  return true;
10650  }
10651 
10652  if (CheckMultiVersionAdditionalRules(S, nullptr, FD, true, MVKind)) {
10653  FD->setInvalidDecl();
10654  return true;
10655  }
10656 
10657  FD->setIsMultiVersion();
10658  return false;
10659 }
10660 
10662  for (const Decl *D = FD->getPreviousDecl(); D; D = D->getPreviousDecl()) {
10664  return true;
10665  }
10666 
10667  return false;
10668 }
10669 
10671  Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA,
10672  bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous) {
10673  const auto *OldTA = OldFD->getAttr<TargetAttr>();
10674  ParsedTargetAttr NewParsed = NewTA->parse();
10675  // Sort order doesn't matter, it just needs to be consistent.
10676  llvm::sort(NewParsed.Features);
10677 
10678  // If the old decl is NOT MultiVersioned yet, and we don't cause that
10679  // to change, this is a simple redeclaration.
10680  if (!NewTA->isDefaultVersion() &&
10681  (!OldTA || OldTA->getFeaturesStr() == NewTA->getFeaturesStr()))
10682  return false;
10683 
10684  // Otherwise, this decl causes MultiVersioning.
10685  if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD, true,
10687  NewFD->setInvalidDecl();
10688  return true;
10689  }
10690 
10691  if (CheckMultiVersionValue(S, NewFD)) {
10692  NewFD->setInvalidDecl();
10693  return true;
10694  }
10695 
10696  // If this is 'default', permit the forward declaration.
10697  if (!OldFD->isMultiVersion() && !OldTA && NewTA->isDefaultVersion()) {
10698  Redeclaration = true;
10699  OldDecl = OldFD;
10700  OldFD->setIsMultiVersion();
10701  NewFD->setIsMultiVersion();
10702  return false;
10703  }
10704 
10705  if (CheckMultiVersionValue(S, OldFD)) {
10706  S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10707  NewFD->setInvalidDecl();
10708  return true;
10709  }
10710 
10711  ParsedTargetAttr OldParsed = OldTA->parse(std::less<std::string>());
10712 
10713  if (OldParsed == NewParsed) {
10714  S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10715  S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10716  NewFD->setInvalidDecl();
10717  return true;
10718  }
10719 
10720  for (const auto *FD : OldFD->redecls()) {
10721  const auto *CurTA = FD->getAttr<TargetAttr>();
10722  // We allow forward declarations before ANY multiversioning attributes, but
10723  // nothing after the fact.
10725  (!CurTA || CurTA->isInherited())) {
10726  S.Diag(FD->getLocation(), diag::err_multiversion_required_in_redecl)
10727  << 0;
10728  S.Diag(NewFD->getLocation(), diag::note_multiversioning_caused_here);
10729  NewFD->setInvalidDecl();
10730  return true;
10731  }
10732  }
10733 
10734  OldFD->setIsMultiVersion();
10735  NewFD->setIsMultiVersion();
10736  Redeclaration = false;
10737  OldDecl = nullptr;
10738  Previous.clear();
10739  return false;
10740 }
10741 
10743  MultiVersionKind New) {
10744  if (Old == New || Old == MultiVersionKind::None ||
10745  New == MultiVersionKind::None)
10746  return true;
10747 
10748  return (Old == MultiVersionKind::CPUDispatch &&
10752 }
10753 
10754 /// Check the validity of a new function declaration being added to an existing
10755 /// multiversioned declaration collection.
10757  Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD,
10758  MultiVersionKind NewMVKind, const TargetAttr *NewTA,
10759  const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec,
10760  const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl,
10762 
10763  MultiVersionKind OldMVKind = OldFD->getMultiVersionKind();
10764  // Disallow mixing of multiversioning types.
10765  if (!MultiVersionTypesCompatible(OldMVKind, NewMVKind)) {
10766  S.Diag(NewFD->getLocation(), diag::err_multiversion_types_mixed);
10767  S.Diag(OldFD->getLocation(), diag::note_previous_declaration);
10768  NewFD->setInvalidDecl();
10769  return true;
10770  }
10771 
10772  ParsedTargetAttr NewParsed;
10773  if (NewTA) {
10774  NewParsed = NewTA->parse();
10775  llvm::sort(NewParsed.Features);
10776  }
10777 
10778  bool UseMemberUsingDeclRules =
10779  S.CurContext->isRecord() && !NewFD->getFriendObjectKind();
10780 
10781  bool MayNeedOverloadableChecks =
10783 
10784  // Next, check ALL non-overloads to see if this is a redeclaration of a
10785  // previous member of the MultiVersion set.
10786  for (NamedDecl *ND : Previous) {
10787  FunctionDecl *CurFD = ND->getAsFunction();
10788  if (!CurFD)
10789  continue;
10790  if (MayNeedOverloadableChecks &&
10791  S.IsOverload(NewFD, CurFD, UseMemberUsingDeclRules))
10792  continue;
10793 
10794  switch (NewMVKind) {
10796  assert(OldMVKind == MultiVersionKind::TargetClones &&
10797  "Only target_clones can be omitted in subsequent declarations");
10798  break;
10799  case MultiVersionKind::Target: {
10800  const auto *CurTA = CurFD->getAttr<TargetAttr>();
10801  if (CurTA->getFeaturesStr() == NewTA->getFeaturesStr()) {
10802  NewFD->setIsMultiVersion();
10803  Redeclaration = true;
10804  OldDecl = ND;
10805  return false;
10806  }
10807 
10808  ParsedTargetAttr CurParsed = CurTA->parse(std::less<std::string>());
10809  if (CurParsed == NewParsed) {
10810  S.Diag(NewFD->getLocation(), diag::err_multiversion_duplicate);
10811  S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10812  NewFD->setInvalidDecl();
10813  return true;
10814  }
10815  break;
10816  }
10818  const auto *CurClones = CurFD->getAttr<TargetClonesAttr>();
10819  Redeclaration = true;
10820  OldDecl = CurFD;
10821  NewFD->setIsMultiVersion();
10822 
10823  if (CurClones && NewClones &&
10824  (CurClones->featuresStrs_size() != NewClones->featuresStrs_size() ||
10825  !std::equal(CurClones->featuresStrs_begin(),
10826  CurClones->featuresStrs_end(),
10827  NewClones->featuresStrs_begin()))) {
10828  S.Diag(NewFD->getLocation(), diag::err_target_clone_doesnt_match);
10829  S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10830  NewFD->setInvalidDecl();
10831  return true;
10832  }
10833 
10834  return false;
10835  }
10838  const auto *CurCPUSpec = CurFD->getAttr<CPUSpecificAttr>();
10839  const auto *CurCPUDisp = CurFD->getAttr<CPUDispatchAttr>();
10840  // Handle CPUDispatch/CPUSpecific versions.
10841  // Only 1 CPUDispatch function is allowed, this will make it go through
10842  // the redeclaration errors.
10843  if (NewMVKind == MultiVersionKind::CPUDispatch &&
10844  CurFD->hasAttr<CPUDispatchAttr>()) {
10845  if (CurCPUDisp->cpus_size() == NewCPUDisp->cpus_size() &&
10846  std::equal(
10847  CurCPUDisp->cpus_begin(), CurCPUDisp->cpus_end(),
10848  NewCPUDisp->cpus_begin(),
10849  [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10850  return Cur->getName() == New->getName();
10851  })) {
10852  NewFD->setIsMultiVersion();
10853  Redeclaration = true;
10854  OldDecl = ND;
10855  return false;
10856  }
10857 
10858  // If the declarations don't match, this is an error condition.
10859  S.Diag(NewFD->getLocation(), diag::err_cpu_dispatch_mismatch);
10860  S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10861  NewFD->setInvalidDecl();
10862  return true;
10863  }
10864  if (NewMVKind == MultiVersionKind::CPUSpecific && CurCPUSpec) {
10865  if (CurCPUSpec->cpus_size() == NewCPUSpec->cpus_size() &&
10866  std::equal(
10867  CurCPUSpec->cpus_begin(), CurCPUSpec->cpus_end(),
10868  NewCPUSpec->cpus_begin(),
10869  [](const IdentifierInfo *Cur, const IdentifierInfo *New) {
10870  return Cur->getName() == New->getName();
10871  })) {
10872  NewFD->setIsMultiVersion();
10873  Redeclaration = true;
10874  OldDecl = ND;
10875  return false;
10876  }
10877 
10878  // Only 1 version of CPUSpecific is allowed for each CPU.
10879  for (const IdentifierInfo *CurII : CurCPUSpec->cpus()) {
10880  for (const IdentifierInfo *NewII : NewCPUSpec->cpus()) {
10881  if (CurII == NewII) {
10882  S.Diag(NewFD->getLocation(), diag::err_cpu_specific_multiple_defs)
10883  << NewII;
10884  S.Diag(CurFD->getLocation(), diag::note_previous_declaration);
10885  NewFD->setInvalidDecl();
10886  return true;
10887  }
10888  }
10889  }
10890  }
10891  break;
10892  }
10893  }
10894  }
10895 
10896  // Else, this is simply a non-redecl case. Checking the 'value' is only
10897  // necessary in the Target case, since The CPUSpecific/Dispatch cases are
10898  // handled in the attribute adding step.
10899  if (NewMVKind == MultiVersionKind::Target &&
10900  CheckMultiVersionValue(S, NewFD)) {
10901  NewFD->setInvalidDecl();
10902  return true;
10903  }
10904 
10905  if (CheckMultiVersionAdditionalRules(S, OldFD, NewFD,
10906  !OldFD->isMultiVersion(), NewMVKind)) {
10907  NewFD->setInvalidDecl();
10908  return true;
10909  }
10910 
10911  // Permit forward declarations in the case where these two are compatible.
10912  if (!OldFD->isMultiVersion()) {
10913  OldFD->setIsMultiVersion();
10914  NewFD->setIsMultiVersion();
10915  Redeclaration = true;
10916  OldDecl = OldFD;
10917  return false;
10918  }
10919 
10920  NewFD->setIsMultiVersion();
10921  Redeclaration = false;
10922  OldDecl = nullptr;
10923  Previous.clear();
10924  return false;
10925 }
10926 
10927 /// Check the validity of a mulitversion function declaration.
10928 /// Also sets the multiversion'ness' of the function itself.
10929 ///
10930 /// This sets NewFD->isInvalidDecl() to true if there was an error.
10931 ///
10932 /// Returns true if there was an error, false otherwise.
10934  bool &Redeclaration, NamedDecl *&OldDecl,
10936  const auto *NewTA = NewFD->getAttr<TargetAttr>();
10937  const auto *NewCPUDisp = NewFD->getAttr<CPUDispatchAttr>();
10938  const auto *NewCPUSpec = NewFD->getAttr<CPUSpecificAttr>();
10939  const auto *NewClones = NewFD->getAttr<TargetClonesAttr>();
10940  MultiVersionKind MVKind = NewFD->getMultiVersionKind();
10941 
10942  // Main isn't allowed to become a multiversion function, however it IS
10943  // permitted to have 'main' be marked with the 'target' optimization hint.
10944  if (NewFD->isMain()) {
10945  if (MVKind != MultiVersionKind::None &&
10946  !(MVKind == MultiVersionKind::Target && !NewTA->isDefaultVersion())) {
10947  S.Diag(NewFD->getLocation(), diag::err_multiversion_not_allowed_on_main);
10948  NewFD->setInvalidDecl();
10949  return true;
10950  }
10951  return false;
10952  }
10953 
10954  if (!OldDecl || !OldDecl->getAsFunction() ||
10955  OldDecl->getDeclContext()->getRedeclContext() !=
10956  NewFD->getDeclContext()->getRedeclContext()) {
10957  // If there's no previous declaration, AND this isn't attempting to cause
10958  // multiversioning, this isn't an error condition.
10959  if (MVKind == MultiVersionKind::None)
10960  return false;
10961  return CheckMultiVersionFirstFunction(S, NewFD, MVKind, NewTA);
10962  }
10963 
10964  FunctionDecl *OldFD = OldDecl->getAsFunction();
10965 
10966  if (!OldFD->isMultiVersion() && MVKind == MultiVersionKind::None)
10967  return false;
10968 
10969  // Multiversioned redeclarations aren't allowed to omit the attribute, except
10970  // for target_clones.
10971  if (OldFD->isMultiVersion() && MVKind == MultiVersionKind::None &&
10973  S.Diag(NewFD->getLocation(), diag::err_multiversion_required_in_redecl)
10975  NewFD->setInvalidDecl();
10976  return true;
10977  }
10978 
10979  if (!OldFD->isMultiVersion()) {
10980  switch (MVKind) {
10982  return CheckTargetCausesMultiVersioning(S, OldFD, NewFD, NewTA,
10983  Redeclaration, OldDecl, Previous);
10985  if (OldFD->isUsed(false)) {
10986  NewFD->setInvalidDecl();
10987  return S.Diag(NewFD->getLocation(), diag::err_multiversion_after_used);
10988  }
10989  OldFD->setIsMultiVersion();
10990  break;
10994  break;
10995  }
10996  }
10997 
10998  // At this point, we have a multiversion function decl (in OldFD) AND an
10999  // appropriate attribute in the current function decl. Resolve that these are
11000  // still compatible with previous declarations.
11001  return CheckMultiVersionAdditionalDecl(S, OldFD, NewFD, MVKind, NewTA,
11002  NewCPUDisp, NewCPUSpec, NewClones,
11003  Redeclaration, OldDecl, Previous);
11004 }
11005 
11006 /// Perform semantic checking of a new function declaration.
11007 ///
11008 /// Performs semantic analysis of the new function declaration
11009 /// NewFD. This routine performs all semantic checking that does not
11010 /// require the actual declarator involved in the declaration, and is
11011 /// used both for the declaration of functions as they are parsed
11012 /// (called via ActOnDeclarator) and for the declaration of functions
11013 /// that have been instantiated via C++ template instantiation (called
11014 /// via InstantiateDecl).
11015 ///
11016 /// \param IsMemberSpecialization whether this new function declaration is
11017 /// a member specialization (that replaces any definition provided by the
11018 /// previous declaration).
11019 ///
11020 /// This sets NewFD->isInvalidDecl() to true if there was an error.
11021 ///
11022 /// \returns true if the function declaration is a redeclaration.
11025  bool IsMemberSpecialization) {
11026  assert(!NewFD->getReturnType()->isVariablyModifiedType() &&
11027  "Variably modified return types are not handled here");
11028 
11029  // Determine whether the type of this function should be merged with
11030  // a previous visible declaration. This never happens for functions in C++,
11031  // and always happens in C if the previous declaration was visible.
11032  bool MergeTypeWithPrevious = !getLangOpts().CPlusPlus &&
11033  !Previous.isShadowed();
11034 
11035  bool Redeclaration = false;
11036  NamedDecl *OldDecl = nullptr;
11037  bool MayNeedOverloadableChecks = false;
11038 
11039  // Merge or overload the declaration with an existing declaration of
11040  // the same name, if appropriate.
11041  if (!Previous.empty()) {
11042  // Determine whether NewFD is an overload of PrevDecl or
11043  // a declaration that requires merging. If it's an overload,
11044  // there's no more work to do here; we'll just add the new
11045  // function to the scope.
11046  if (!AllowOverloadingOfFunction(Previous, Context, NewFD)) {
11047  NamedDecl *Candidate = Previous.getRepresentativeDecl();
11048  if (shouldLinkPossiblyHiddenDecl(Candidate, NewFD)) {
11049  Redeclaration = true;
11050  OldDecl = Candidate;
11051  }
11052  } else {
11053  MayNeedOverloadableChecks = true;
11054  switch (CheckOverload(S, NewFD, Previous, OldDecl,
11055  /*NewIsUsingDecl*/ false)) {
11056  case Ovl_Match:
11057  Redeclaration = true;
11058  break;
11059 
11060  case Ovl_NonFunction:
11061  Redeclaration = true;
11062  break;
11063 
11064  case Ovl_Overload:
11065  Redeclaration = false;
11066  break;
11067  }
11068  }
11069  }
11070 
11071  // Check for a previous extern "C" declaration with this name.
11072  if (!Redeclaration &&
11074  if (!Previous.empty()) {
11075  // This is an extern "C" declaration with the same name as a previous
11076  // declaration, and thus redeclares that entity...
11077  Redeclaration = true;
11078  OldDecl = Previous.getFoundDecl();
11079  MergeTypeWithPrevious = false;
11080 
11081  // ... except in the presence of __attribute__((overloadable)).
11082  if (OldDecl->hasAttr<OverloadableAttr>() ||
11083  NewFD->hasAttr<OverloadableAttr>()) {
11084  if (IsOverload(NewFD, cast<FunctionDecl>(OldDecl), false)) {
11085  MayNeedOverloadableChecks = true;
11086  Redeclaration = false;
11087  OldDecl = nullptr;
11088  }
11089  }
11090  }
11091  }
11092 
11093  if (CheckMultiVersionFunction(*this, NewFD, Redeclaration, OldDecl, Previous))
11094  return Redeclaration;
11095 
11096  // PPC MMA non-pointer types are not allowed as function return types.
11097  if (Context.getTargetInfo().getTriple().isPPC64() &&
11098  CheckPPCMMAType(NewFD->getReturnType(), NewFD->getLocation())) {
11099  NewFD->setInvalidDecl();
11100  }
11101 
11102  // C++11 [dcl.constexpr]p8:
11103  // A constexpr specifier for a non-static member function that is not
11104  // a constructor declares that member function to be const.
11105  //
11106  // This needs to be delayed until we know whether this is an out-of-line
11107  // definition of a static member function.
11108  //
11109  // This rule is not present in C++1y, so we produce a backwards
11110  // compatibility warning whenever it happens in C++11.
11111  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
11112  if (!getLangOpts().CPlusPlus14 && MD && MD->isConstexpr() &&
11113  !MD->isStatic() && !isa<CXXConstructorDecl>(MD) &&
11114  !isa<CXXDestructorDecl>(MD) && !MD->getMethodQualifiers().hasConst()) {
11115  CXXMethodDecl *OldMD = nullptr;
11116  if (OldDecl)
11117  OldMD = dyn_cast_or_null<CXXMethodDecl>(OldDecl->getAsFunction());
11118  if (!OldMD || !OldMD->isStatic()) {
11119  const FunctionProtoType *FPT =
11120  MD->getType()->castAs<FunctionProtoType>();
11122  EPI.TypeQuals.addConst();
11123  MD->setType(Context.getFunctionType(FPT->getReturnType(),
11124  FPT->getParamTypes(), EPI));
11125 
11126  // Warn that we did this, if we're not performing template instantiation.
11127  // In that case, we'll have warned already when the template was defined.
11128  if (!inTemplateInstantiation()) {
11129  SourceLocation AddConstLoc;
11130  if (FunctionTypeLoc FTL = MD->getTypeSourceInfo()->getTypeLoc()
11132  AddConstLoc = getLocForEndOfToken(FTL.getRParenLoc());
11133 
11134  Diag(MD->getLocation(), diag::warn_cxx14_compat_constexpr_not_const)
11135  << FixItHint::CreateInsertion(AddConstLoc, " const");
11136  }
11137  }
11138  }
11139 
11140  if (Redeclaration) {
11141  // NewFD and OldDecl represent declarations that need to be
11142  // merged.
11143  if (MergeFunctionDecl(NewFD, OldDecl, S, MergeTypeWithPrevious)) {
11144  NewFD->setInvalidDecl();
11145  return Redeclaration;
11146  }
11147 
11148  Previous.clear();
11149  Previous.addDecl(OldDecl);
11150 
11151  if (FunctionTemplateDecl *OldTemplateDecl =
11152  dyn_cast<FunctionTemplateDecl>(OldDecl)) {
11153  auto *OldFD = OldTemplateDecl->getTemplatedDecl();
11154  FunctionTemplateDecl *NewTemplateDecl
11155  = NewFD->getDescribedFunctionTemplate();
11156  assert(NewTemplateDecl && "Template/non-template mismatch");
11157 
11158  // The call to MergeFunctionDecl above may have created some state in
11159  // NewTemplateDecl that needs to be merged with OldTemplateDecl before we
11160  // can add it as a redeclaration.
11161  NewTemplateDecl->mergePrevDecl(OldTemplateDecl);
11162 
11163  NewFD->setPreviousDeclaration(OldFD);
11164  if (NewFD->isCXXClassMember()) {
11165  NewFD->setAccess(OldTemplateDecl->getAccess());
11166  NewTemplateDecl->setAccess(OldTemplateDecl->getAccess());
11167  }
11168 
11169  // If this is an explicit specialization of a member that is a function
11170  // template, mark it as a member specialization.
11171  if (IsMemberSpecialization &&
11172  NewTemplateDecl->getInstantiatedFromMemberTemplate()) {
11173  NewTemplateDecl->setMemberSpecialization();
11174  assert(OldTemplateDecl->isMemberSpecialization());
11175  // Explicit specializations of a member template do not inherit deleted
11176  // status from the parent member template that they are specializing.
11177  if (OldFD->isDeleted()) {
11178  // FIXME: This assert will not hold in the presence of modules.
11179  assert(OldFD->getCanonicalDecl() == OldFD);
11180  // FIXME: We need an update record for this AST mutation.
11181  OldFD->setDeletedAsWritten(false);
11182  }
11183  }
11184 
11185  } else {
11186  if (shouldLinkDependentDeclWithPrevious(NewFD, OldDecl)) {
11187  auto *OldFD = cast<FunctionDecl>(OldDecl);
11188  // This needs to happen first so that 'inline' propagates.
11189  NewFD->setPreviousDeclaration(OldFD);
11190  if (NewFD->isCXXClassMember())
11191  NewFD->setAccess(OldFD->getAccess());
11192  }
11193  }
11194  } else if (!getLangOpts().CPlusPlus && MayNeedOverloadableChecks &&
11195  !NewFD->getAttr<OverloadableAttr>()) {
11196  assert((Previous.empty() ||
11197  llvm::any_of(Previous,
11198  [](const NamedDecl *ND) {
11199  return ND->hasAttr<OverloadableAttr>();
11200  })) &&
11201  "Non-redecls shouldn't happen without overloadable present");
11202 
11203  auto OtherUnmarkedIter = llvm::find_if(Previous, [](const NamedDecl *ND) {
11204  const auto *FD = dyn_cast<FunctionDecl>(ND);
11205  return FD && !FD->hasAttr<OverloadableAttr>();
11206  });
11207 
11208  if (OtherUnmarkedIter != Previous.end()) {
11209  Diag(NewFD->getLocation(),
11210  diag::err_attribute_overloadable_multiple_unmarked_overloads);
11211  Diag((*OtherUnmarkedIter)->getLocation(),
11212  diag::note_attribute_overloadable_prev_overload)
11213  << false;
11214 
11215  NewFD->addAttr(OverloadableAttr::CreateImplicit(Context));
11216  }
11217  }
11218 
11219  if (LangOpts.OpenMP)
11220  ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(NewFD);
11221 
11222  // Semantic checking for this function declaration (in isolation).
11223 
11224  if (getLangOpts().CPlusPlus) {
11225  // C++-specific checks.
11226  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD)) {
11227  CheckConstructor(Constructor);
11228  } else if (CXXDestructorDecl *Destructor =
11229  dyn_cast<CXXDestructorDecl>(NewFD)) {
11230  CXXRecordDecl *Record = Destructor->getParent();
11231  QualType ClassType = Context.getTypeDeclType(Record);
11232 
11233  // FIXME: Shouldn't we be able to perform this check even when the class
11234  // type is dependent? Both gcc and edg can handle that.
11235  if (!ClassType->isDependentType()) {
11236  DeclarationName Name
11238  Context.getCanonicalType(ClassType));
11239  if (NewFD->getDeclName() != Name) {
11240  Diag(NewFD->getLocation(), diag::err_destructor_name);
11241  NewFD->setInvalidDecl();
11242  return Redeclaration;
11243  }
11244  }
11245  } else if (auto *Guide = dyn_cast<CXXDeductionGuideDecl>(NewFD)) {
11246  if (auto *TD = Guide->getDescribedFunctionTemplate())
11247  CheckDeductionGuideTemplate(TD);
11248 
11249  // A deduction guide is not on the list of entities that can be
11250  // explicitly specialized.
11251  if (Guide->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
11252  Diag(Guide->getBeginLoc(), diag::err_deduction_guide_specialized)
11253  << /*explicit specialization*/ 1;
11254  }
11255 
11256  // Find any virtual functions that this function overrides.
11257  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD)) {
11258  if (!Method->isFunctionTemplateSpecialization() &&
11259  !Method->getDescribedFunctionTemplate() &&
11260  Method->isCanonicalDecl()) {
11261  AddOverriddenMethods(Method->getParent(), Method);
11262  }
11263  if (Method->isVirtual() && NewFD->getTrailingRequiresClause())
11264  // C++2a [class.virtual]p6
11265  // A virtual method shall not have a requires-clause.
11267  diag::err_constrained_virtual_method);
11268 
11269  if (Method->isStatic())
11270  checkThisInStaticMemberFunctionType(Method);
11271  }
11272 
11273  if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
11274  ActOnConversionDeclarator(Conversion);
11275 
11276  // Extra checking for C++ overloaded operators (C++ [over.oper]).
11277  if (NewFD->isOverloadedOperator() &&
11278  CheckOverloadedOperatorDeclaration(NewFD)) {
11279  NewFD->setInvalidDecl();
11280  return Redeclaration;
11281  }
11282 
11283  // Extra checking for C++0x literal operators (C++0x [over.literal]).
11284  if (NewFD->getLiteralIdentifier() &&
11285  CheckLiteralOperatorDeclaration(NewFD)) {
11286  NewFD->setInvalidDecl();
11287  return Redeclaration;
11288  }
11289 
11290  // In C++, check default arguments now that we have merged decls. Unless
11291  // the lexical context is the class, because in this case this is done
11292  // during delayed parsing anyway.
11293  if (!CurContext->isRecord())
11294  CheckCXXDefaultArguments(NewFD);
11295 
11296  // If this function is declared as being extern "C", then check to see if
11297  // the function returns a UDT (class, struct, or union type) that is not C
11298  // compatible, and if it does, warn the user.
11299  // But, issue any diagnostic on the first declaration only.
11300  if (Previous.empty() && NewFD->isExternC()) {
11301  QualType R = NewFD->getReturnType();
11302  if (R->isIncompleteType() && !R->isVoidType())
11303  Diag(NewFD->getLocation(), diag::warn_return_value_udt_incomplete)
11304  << NewFD << R;
11305  else if (!R.isPODType(Context) && !R->isVoidType() &&
11306  !R->isObjCObjectPointerType())
11307  Diag(NewFD->getLocation(), diag::warn_return_value_udt) << NewFD << R;
11308  }
11309 
11310  // C++1z [dcl.fct]p6:
11311  // [...] whether the function has a non-throwing exception-specification
11312  // [is] part of the function type
11313  //
11314  // This results in an ABI break between C++14 and C++17 for functions whose
11315  // declared type includes an exception-specification in a parameter or
11316  // return type. (Exception specifications on the function itself are OK in
11317  // most cases, and exception specifications are not permitted in most other
11318  // contexts where they could make it into a mangling.)
11319  if (!getLangOpts().CPlusPlus17 && !NewFD->getPrimaryTemplate()) {
11320  auto HasNoexcept = [&](QualType T) -> bool {
11321  // Strip off declarator chunks that could be between us and a function
11322  // type. We don't need to look far, exception specifications are very
11323  // restricted prior to C++17.
11324  if (auto *RT = T->getAs<ReferenceType>())
11325  T = RT->getPointeeType();
11326  else if (T->isAnyPointerType())
11327  T = T->getPointeeType();
11328  else if (auto *MPT = T->getAs<MemberPointerType>())
11329  T = MPT->getPointeeType();
11330  if (auto *FPT = T->getAs<FunctionProtoType>())
11331  if (FPT->isNothrow())
11332  return true;
11333  return false;
11334  };
11335 
11336  auto *FPT = NewFD->getType()->castAs<FunctionProtoType>();
11337  bool AnyNoexcept = HasNoexcept(FPT->getReturnType());
11338  for (QualType T : FPT->param_types())
11339  AnyNoexcept |= HasNoexcept(T);
11340  if (AnyNoexcept)
11341  Diag(NewFD->getLocation(),
11342  diag::warn_cxx17_compat_exception_spec_in_signature)
11343  << NewFD;
11344  }
11345 
11346  if (!Redeclaration && LangOpts.CUDA)
11347  checkCUDATargetOverload(NewFD, Previous);
11348  }
11349  return Redeclaration;
11350 }
11351 
11352 void Sema::CheckMain(FunctionDecl* FD, const DeclSpec& DS) {
11353  // C++11 [basic.start.main]p3:
11354  // A program that [...] declares main to be inline, static or
11355  // constexpr is ill-formed.
11356  // C11 6.7.4p4: In a hosted environment, no function specifier(s) shall
11357  // appear in a declaration of main.
11358  // static main is not an error under C99, but we should warn about it.
11359  // We accept _Noreturn main as an extension.
11360  if (FD->getStorageClass() == SC_Static)
11361  Diag(DS.getStorageClassSpecLoc(), getLangOpts().CPlusPlus
11362  ? diag::err_static_main : diag::warn_static_main)
11364  if (FD->isInlineSpecified())
11365  Diag(DS.getInlineSpecLoc(), diag::err_inline_main)
11367  if (DS.isNoreturnSpecified()) {
11368  SourceLocation NoreturnLoc = DS.getNoreturnSpecLoc();
11369  SourceRange NoreturnRange(NoreturnLoc, getLocForEndOfToken(NoreturnLoc));
11370  Diag(NoreturnLoc, diag::ext_noreturn_main);
11371  Diag(NoreturnLoc, diag::note_main_remove_noreturn)
11372  << FixItHint::CreateRemoval(NoreturnRange);
11373  }
11374  if (FD->isConstexpr()) {
11375  Diag(DS.getConstexprSpecLoc(), diag::err_constexpr_main)
11376  << FD->isConsteval()
11379  }
11380 
11381  if (getLangOpts().OpenCL) {
11382  Diag(FD->getLocation(), diag::err_opencl_no_main)
11383  << FD->hasAttr<OpenCLKernelAttr>();
11384  FD->setInvalidDecl();
11385  return;
11386  }
11387 
11388  QualType T = FD->getType();
11389  assert(T->isFunctionType() && "function decl is not of function type");
11390  const FunctionType* FT = T->castAs<FunctionType>();
11391 
11392  // Set default calling convention for main()
11393  if (FT->getCallConv() != CC_C) {
11394  FT = Context.adjustFunctionType(FT, FT->getExtInfo().withCallingConv(CC_C));
11395  FD->setType(QualType(FT, 0));
11396  T = Context.getCanonicalType(FD->getType());
11397  }
11398 
11399  if (getLangOpts().GNUMode && !getLangOpts().CPlusPlus) {
11400  // In C with GNU extensions we allow main() to have non-integer return
11401  // type, but we should warn about the extension, and we disable the
11402  // implicit-return-zero rule.
11403 
11404  // GCC in C mode accepts qualified 'int'.
11405  if (Context.hasSameUnqualifiedType(FT->getReturnType(), Context.IntTy))
11406  FD->setHasImplicitReturnZero(true);
11407  else {
11408  Diag(FD->getTypeSpecStartLoc(), diag::ext_main_returns_nonint);
11409  SourceRange RTRange = FD->getReturnTypeSourceRange();
11410  if (RTRange.isValid())
11411  Diag(RTRange.getBegin(), diag::note_main_change_return_type)
11412  << FixItHint::CreateReplacement(RTRange, "int");
11413  }
11414  } else {
11415  // In C and C++, main magically returns 0 if you fall off the end;
11416  // set the flag which tells us that.
11417  // This is C++ [basic.start.main]p5 and C99 5.1.2.2.3.
11418 
11419  // All the standards say that main() should return 'int'.
11420  if (Context.hasSameType(FT->getReturnType(), Context.IntTy))
11421  FD->setHasImplicitReturnZero(true);
11422  else {
11423  // Otherwise, this is just a flat-out error.
11424  SourceRange RTRange = FD->getReturnTypeSourceRange();
11425  Diag(FD->getTypeSpecStartLoc(), diag::err_main_returns_nonint)
11426  << (RTRange.isValid() ? FixItHint::CreateReplacement(RTRange, "int")
11427  : FixItHint());
11428  FD->setInvalidDecl(true);
11429  }
11430  }
11431 
11432  // Treat protoless main() as nullary.
11433  if (isa<FunctionNoProtoType>(FT)) return;
11434 
11435  const FunctionProtoType* FTP = cast<const FunctionProtoType>(FT);
11436  unsigned nparams = FTP->getNumParams();
11437  assert(FD->getNumParams() == nparams);
11438 
11439  bool HasExtraParameters = (nparams > 3);
11440 
11441  if (FTP->isVariadic()) {
11442  Diag(FD->getLocation(), diag::ext_variadic_main);
11443  // FIXME: if we had information about the location of the ellipsis, we
11444  // could add a FixIt hint to remove it as a parameter.
11445  }
11446 
11447  // Darwin passes an undocumented fourth argument of type char**. If
11448  // other platforms start sprouting these, the logic below will start
11449  // getting shifty.
11450  if (nparams == 4 && Context.getTargetInfo().getTriple().isOSDarwin())
11451  HasExtraParameters = false;
11452 
11453  if (HasExtraParameters) {
11454  Diag(FD->getLocation(), diag::err_main_surplus_args) << nparams;
11455  FD->setInvalidDecl(true);
11456  nparams = 3;
11457  }
11458 
11459  // FIXME: a lot of the following diagnostics would be improved
11460  // if we had some location information about types.
11461 
11462  QualType CharPP =
11463  Context.getPointerType(Context.getPointerType(Context.CharTy));
11464  QualType Expected[] = { Context.IntTy, CharPP, CharPP, CharPP };
11465 
11466  for (unsigned i = 0; i < nparams; ++i) {
11467  QualType AT = FTP->getParamType(i);
11468 
11469  bool mismatch = true;
11470 
11471  if (Context.hasSameUnqualifiedType(AT, Expected[i]))
11472  mismatch = false;
11473  else if (Expected[i] == CharPP) {
11474  // As an extension, the following forms are okay:
11475  // char const **
11476  // char const * const *
11477  // char * const *
11478 
11479  QualifierCollector qs;
11480  const PointerType* PT;
11481  if ((PT = qs.strip(AT)->getAs<PointerType>()) &&
11482  (PT = qs.strip(PT->getPointeeType())->getAs<PointerType>()) &&
11483  Context.hasSameType(QualType(qs.strip(PT->getPointeeType()), 0),
11484  Context.CharTy)) {
11485  qs.removeConst();
11486  mismatch = !qs.empty();
11487  }
11488  }
11489 
11490  if (mismatch) {
11491  Diag(FD->getLocation(), diag::err_main_arg_wrong) << i << Expected[i];
11492  // TODO: suggest replacing given type with expected type
11493  FD->setInvalidDecl(true);
11494  }
11495  }
11496 
11497  if (nparams == 1 && !FD->isInvalidDecl()) {
11498  Diag(FD->getLocation(), diag::warn_main_one_arg);
11499  }
11500 
11501  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11502  Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11503  FD->setInvalidDecl();
11504  }
11505 }
11506 
11507 static bool isDefaultStdCall(FunctionDecl *FD, Sema &S) {
11508 
11509  // Default calling convention for main and wmain is __cdecl
11510  if (FD->getName() == "main" || FD->getName() == "wmain")
11511  return false;
11512 
11513  // Default calling convention for MinGW is __cdecl
11514  const llvm::Triple &T = S.Context.getTargetInfo().getTriple();
11515  if (T.isWindowsGNUEnvironment())
11516  return false;
11517 
11518  // Default calling convention for WinMain, wWinMain and DllMain
11519  // is __stdcall on 32 bit Windows
11520  if (T.isOSWindows() && T.getArch() == llvm::Triple::x86)
11521  return true;
11522 
11523  return false;
11524 }
11525 
11527  QualType T = FD->getType();
11528  assert(T->isFunctionType() && "function decl is not of function type");
11529  const FunctionType *FT = T->castAs<FunctionType>();
11530 
11531  // Set an implicit return of 'zero' if the function can return some integral,
11532  // enumeration, pointer or nullptr type.
11534  FT->getReturnType()->isAnyPointerType() ||
11535  FT->getReturnType()->isNullPtrType())
11536  // DllMain is exempt because a return value of zero means it failed.
11537  if (FD->getName() != "DllMain")
11538  FD->setHasImplicitReturnZero(true);
11539 
11540  // Explicity specified calling conventions are applied to MSVC entry points
11541  if (!hasExplicitCallingConv(T)) {
11542  if (isDefaultStdCall(FD, *this)) {
11543  if (FT->getCallConv() != CC_X86StdCall) {
11544  FT = Context.adjustFunctionType(
11546  FD->setType(QualType(FT, 0));
11547  }
11548  } else if (FT->getCallConv() != CC_C) {
11549  FT = Context.adjustFunctionType(FT,
11551  FD->setType(QualType(FT, 0));
11552  }
11553  }
11554 
11555  if (!FD->isInvalidDecl() && FD->getDescribedFunctionTemplate()) {
11556  Diag(FD->getLocation(), diag::err_mainlike_template_decl) << FD;
11557  FD->setInvalidDecl();
11558  }
11559 }
11560 
11562  // FIXME: Need strict checking. In C89, we need to check for
11563  // any assignment, increment, decrement, function-calls, or
11564  // commas outside of a sizeof. In C99, it's the same list,
11565  // except that the aforementioned are allowed in unevaluated
11566  // expressions. Everything else falls under the
11567  // "may accept other forms of constant expressions" exception.
11568  //
11569  // Regular C++ code will not end up here (exceptions: language extensions,
11570  // OpenCL C++ etc), so the constant expression rules there don't matter.
11571  if (Init->isValueDependent()) {
11572  assert(Init->containsErrors() &&
11573  "Dependent code should only occur in error-recovery path.");
11574  return true;
11575  }
11576  const Expr *Culprit;
11577  if (Init->isConstantInitializer(Context, false, &Culprit))
11578  return false;
11579  Diag(Culprit->getExprLoc(), diag::err_init_element_not_constant)
11580  << Culprit->getSourceRange();
11581  return true;
11582 }
11583 
11584 namespace {
11585  // Visits an initialization expression to see if OrigDecl is evaluated in
11586  // its own initialization and throws a warning if it does.
11587  class SelfReferenceChecker
11588  : public EvaluatedExprVisitor<SelfReferenceChecker> {
11589  Sema &S;
11590  Decl *OrigDecl;
11591  bool isRecordType;
11592  bool isPODType;
11593  bool isReferenceType;
11594 
11595  bool isInitList;
11596  llvm::SmallVector<unsigned, 4> InitFieldIndex;
11597 
11598  public:
11600 
11601  SelfReferenceChecker(Sema &S, Decl *OrigDecl) : Inherited(S.Context),
11602  S(S), OrigDecl(OrigDecl) {
11603  isPODType = false;
11604  isRecordType = false;
11605  isReferenceType = false;
11606  isInitList = false;
11607  if (ValueDecl *VD = dyn_cast<ValueDecl>(OrigDecl)) {
11608  isPODType = VD->getType().isPODType(S.Context);
11609  isRecordType = VD->getType()->isRecordType();
11610  isReferenceType = VD->getType()->isReferenceType();
11611  }
11612  }
11613 
11614  // For most expressions, just call the visitor. For initializer lists,
11615  // track the index of the field being initialized since fields are
11616  // initialized in order allowing use of previously initialized fields.
11617  void CheckExpr(Expr *E) {
11618  InitListExpr *InitList = dyn_cast<InitListExpr>(E);
11619  if (!InitList) {
11620  Visit(E);
11621  return;
11622  }
11623 
11624  // Track and increment the index here.
11625  isInitList = true;
11626  InitFieldIndex.push_back(0);
11627  for (auto Child : InitList->children()) {
11628  CheckExpr(cast<Expr>(Child));
11629  ++InitFieldIndex.back();
11630  }
11631  InitFieldIndex.pop_back();
11632  }
11633 
11634  // Returns true if MemberExpr is checked and no further checking is needed.
11635  // Returns false if additional checking is required.
11636  bool CheckInitListMemberExpr(MemberExpr *E, bool CheckReference) {
11638  Expr *Base = E;
11639  bool ReferenceField = false;
11640 
11641  // Get the field members used.
11642  while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11643  FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
11644  if (!FD)
11645  return false;
11646  Fields.push_back(FD);
11647  if (FD->getType()->isReferenceType())
11648  ReferenceField = true;
11649  Base = ME->getBase()->IgnoreParenImpCasts();
11650  }
11651 
11652  // Keep checking only if the base Decl is the same.
11653  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base);
11654  if (!DRE || DRE->getDecl() != OrigDecl)
11655  return false;
11656 
11657  // A reference field can be bound to an unininitialized field.
11658  if (CheckReference && !ReferenceField)
11659  return true;
11660 
11661  // Convert FieldDecls to their index number.
11662  llvm::SmallVector<unsigned, 4> UsedFieldIndex;
11663  for (const FieldDecl *I : llvm::reverse(Fields))
11664  UsedFieldIndex.push_back(I->getFieldIndex());
11665 
11666  // See if a warning is needed by checking the first difference in index
11667  // numbers. If field being used has index less than the field being
11668  // initialized, then the use is safe.
11669  for (auto UsedIter = UsedFieldIndex.begin(),
11670  UsedEnd = UsedFieldIndex.end(),
11671  OrigIter = InitFieldIndex.begin(),
11672  OrigEnd = InitFieldIndex.end();
11673  UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
11674  if (*UsedIter < *OrigIter)
11675  return true;
11676  if (*UsedIter > *OrigIter)
11677  break;
11678  }
11679 
11680  // TODO: Add a different warning which will print the field names.
11681  HandleDeclRefExpr(DRE);
11682  return true;
11683  }
11684 
11685  // For most expressions, the cast is directly above the DeclRefExpr.
11686  // For conditional operators, the cast can be outside the conditional
11687  // operator if both expressions are DeclRefExpr's.
11688  void HandleValue(Expr *E) {
11689  E = E->IgnoreParens();
11690  if (DeclRefExpr* DRE = dyn_cast<DeclRefExpr>(E)) {
11691  HandleDeclRefExpr(DRE);
11692  return;
11693  }
11694 
11695  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
11696  Visit(CO->getCond());
11697  HandleValue(CO->getTrueExpr());
11698  HandleValue(CO->getFalseExpr());
11699  return;
11700  }
11701 
11702  if (BinaryConditionalOperator *BCO =
11703  dyn_cast<BinaryConditionalOperator>(E)) {
11704  Visit(BCO->getCond());
11705  HandleValue(BCO->getFalseExpr());
11706  return;
11707  }
11708 
11709  if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
11710  HandleValue(OVE->getSourceExpr());
11711  return;
11712  }
11713 
11714  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
11715  if (BO->getOpcode() == BO_Comma) {
11716  Visit(BO->getLHS());
11717  HandleValue(BO->getRHS());
11718  return;
11719  }
11720  }
11721 
11722  if (isa<MemberExpr>(E)) {
11723  if (isInitList) {
11724  if (CheckInitListMemberExpr(cast<MemberExpr>(E),
11725  false /*CheckReference*/))
11726  return;
11727  }
11728 
11729  Expr *Base = E->IgnoreParenImpCasts();
11730  while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11731  // Check for static member variables and don't warn on them.
11732  if (!isa<FieldDecl>(ME->getMemberDecl()))
11733  return;
11734  Base = ME->getBase()->IgnoreParenImpCasts();
11735  }
11736  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base))
11737  HandleDeclRefExpr(DRE);
11738  return;
11739  }
11740 
11741  Visit(E);
11742  }
11743 
11744  // Reference types not handled in HandleValue are handled here since all
11745  // uses of references are bad, not just r-value uses.
11746  void VisitDeclRefExpr(DeclRefExpr *E) {
11747  if (isReferenceType)
11748  HandleDeclRefExpr(E);
11749  }
11750 
11751  void VisitImplicitCastExpr(ImplicitCastExpr *E) {
11752  if (E->getCastKind() == CK_LValueToRValue) {
11753  HandleValue(E->getSubExpr());
11754  return;
11755  }
11756 
11757  Inherited::VisitImplicitCastExpr(E);
11758  }
11759 
11760  void VisitMemberExpr(MemberExpr *E) {
11761  if (isInitList) {
11762  if (CheckInitListMemberExpr(E, true /*CheckReference*/))
11763  return;
11764  }
11765 
11766  // Don't warn on arrays since they can be treated as pointers.
11767  if (E->getType()->canDecayToPointerType()) return;
11768 
11769  // Warn when a non-static method call is followed by non-static member
11770  // field accesses, which is followed by a DeclRefExpr.
11771  CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl());
11772  bool Warn = (MD && !MD->isStatic());
11773  Expr *Base = E->getBase()->IgnoreParenImpCasts();
11774  while (MemberExpr *ME = dyn_cast<MemberExpr>(Base)) {
11775  if (!isa<FieldDecl>(ME->getMemberDecl()))
11776  Warn = false;
11777  Base = ME->getBase()->IgnoreParenImpCasts();
11778  }
11779 
11780  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) {
11781  if (Warn)
11782  HandleDeclRefExpr(DRE);
11783  return;
11784  }
11785 
11786  // The base of a MemberExpr is not a MemberExpr or a DeclRefExpr.
11787  // Visit that expression.
11788  Visit(Base);
11789  }
11790 
11791  void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
11792  Expr *Callee = E->getCallee();
11793 
11794  if (isa<UnresolvedLookupExpr>(Callee))
11795  return Inherited::VisitCXXOperatorCallExpr(E);
11796 
11797  Visit(Callee);
11798  for (auto Arg: E->arguments())
11799  HandleValue(Arg->IgnoreParenImpCasts());
11800  }
11801 
11802  void VisitUnaryOperator(UnaryOperator *E) {
11803  // For POD record types, addresses of its own members are well-defined.
11804  if (E->getOpcode() == UO_AddrOf && isRecordType &&
11805  isa<MemberExpr>(E->getSubExpr()->IgnoreParens())) {
11806  if (!isPODType)
11807  HandleValue(E->getSubExpr());
11808  return;
11809  }
11810 
11811  if (E->isIncrementDecrementOp()) {
11812  HandleValue(E->getSubExpr());
11813  return;
11814  }
11815 
11816  Inherited::VisitUnaryOperator(E);
11817  }
11818 
11819  void VisitObjCMessageExpr(ObjCMessageExpr *E) {}
11820 
11821  void VisitCXXConstructExpr(CXXConstructExpr *E) {
11822  if (E->getConstructor()->isCopyConstructor()) {
11823  Expr *ArgExpr = E->getArg(0);
11824  if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
11825  if (ILE->getNumInits() == 1)
11826  ArgExpr = ILE->getInit(0);
11827  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
11828  if (ICE->getCastKind() == CK_NoOp)
11829  ArgExpr = ICE->getSubExpr();
11830  HandleValue(ArgExpr);
11831  return;
11832  }
11833  Inherited::VisitCXXConstructExpr(E);
11834  }
11835 
11836  void VisitCallExpr(CallExpr *E) {
11837  // Treat std::move as a use.
11838  if (E->isCallToStdMove()) {
11839  HandleValue(E->getArg(0));
11840  return;
11841  }
11842 
11843  Inherited::VisitCallExpr(E);
11844  }
11845 
11846  void VisitBinaryOperator(BinaryOperator *E) {
11847  if (E->isCompoundAssignmentOp()) {
11848  HandleValue(E->getLHS());
11849  Visit(E->getRHS());
11850  return;
11851  }
11852 
11853  Inherited::VisitBinaryOperator(E);
11854  }
11855 
11856  // A custom visitor for BinaryConditionalOperator is needed because the
11857  // regular visitor would check the condition and true expression separately
11858  // but both point to the same place giving duplicate diagnostics.
11859  void VisitBinaryConditionalOperator(BinaryConditionalOperator *E) {
11860  Visit(E->getCond());
11861  Visit(E->getFalseExpr());
11862  }
11863 
11864  void HandleDeclRefExpr(DeclRefExpr *DRE) {
11865  Decl* ReferenceDecl = DRE->getDecl();
11866  if (OrigDecl != ReferenceDecl) return;
11867  unsigned diag;
11868  if (isReferenceType) {
11869  diag = diag::warn_uninit_self_reference_in_reference_init;
11870  } else if (cast<VarDecl>(OrigDecl)->isStaticLocal()) {
11871  diag = diag::warn_static_self_reference_in_init;
11872  } else if (isa<TranslationUnitDecl>(OrigDecl->getDeclContext()) ||
11873  isa<NamespaceDecl>(OrigDecl->getDeclContext()) ||
11874  DRE->getDecl()->getType()->isRecordType()) {
11875  diag = diag::warn_uninit_self_reference_in_init;
11876  } else {
11877  // Local variables will be handled by the CFG analysis.
11878  return;
11879  }
11880 
11881  S.DiagRuntimeBehavior(DRE->getBeginLoc(), DRE,
11882  S.PDiag(diag)
11883  << DRE->getDecl() << OrigDecl->getLocation()
11884  << DRE->getSourceRange());
11885  }
11886  };
11887 
11888  /// CheckSelfReference - Warns if OrigDecl is used in expression E.
11889  static void CheckSelfReference(Sema &S, Decl* OrigDecl, Expr *E,
11890  bool DirectInit) {
11891  // Parameters arguments are occassionially constructed with itself,
11892  // for instance, in recursive functions. Skip them.
11893  if (isa<ParmVarDecl>(OrigDecl))
11894  return;
11895 
11896  E = E->IgnoreParens();
11897 
11898  // Skip checking T a = a where T is not a record or reference type.
11899  // Doing so is a way to silence uninitialized warnings.
11900  if (!DirectInit && !cast<VarDecl>(OrigDecl)->getType()->isRecordType())
11901  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E))
11902  if (ICE->getCastKind() == CK_LValueToRValue)
11903  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(ICE->getSubExpr()))
11904  if (DRE->getDecl() == OrigDecl)
11905  return;
11906 
11907  SelfReferenceChecker(S, OrigDecl).CheckExpr(E);
11908  }
11909 } // end anonymous namespace
11910 
11911 namespace {
11912  // Simple wrapper to add the name of a variable or (if no variable is
11913  // available) a DeclarationName into a diagnostic.
11914  struct VarDeclOrName {
11915  VarDecl *VDecl;
11916  DeclarationName Name;
11917 
11918  friend const Sema::SemaDiagnosticBuilder &
11919  operator<<(const Sema::SemaDiagnosticBuilder &Diag, VarDeclOrName VN) {
11920  return VN.VDecl ? Diag << VN.VDecl : Diag << VN.Name;
11921  }
11922  };
11923 } // end anonymous namespace
11924 
11927  TypeSourceInfo *TSI,
11928  SourceRange Range, bool DirectInit,
11929  Expr *Init) {
11930  bool IsInitCapture = !VDecl;
11931  assert((!VDecl || !VDecl->isInitCapture()) &&
11932  "init captures are expected to be deduced prior to initialization");
11933 
11934  VarDeclOrName VN{VDecl, Name};
11935 
11937  assert(Deduced && "deduceVarTypeFromInitializer for non-deduced type");
11938 
11939  // C++11 [dcl.spec.auto]p3
11940  if (!Init) {
11941  assert(VDecl && "no init for init capture deduction?");
11942 
11943  // Except for class argument deduction, and then for an initializing
11944  // declaration only, i.e. no static at class scope or extern.
11945  if (!isa<DeducedTemplateSpecializationType>(Deduced) ||
11946  VDecl->hasExternalStorage() ||
11947  VDecl->isStaticDataMember()) {
11948  Diag(VDecl->getLocation(), diag::err_auto_var_requires_init)
11949  << VDecl->getDeclName() << Type;
11950  return QualType();
11951  }
11952  }
11953 
11954  ArrayRef<Expr*> DeduceInits;
11955  if (Init)
11956  DeduceInits = Init;
11957 
11958  if (DirectInit) {
11959  if (auto *PL = dyn_cast_or_null<ParenListExpr>(Init))
11960  DeduceInits = PL->exprs();
11961  }
11962 
11963  if (isa<DeducedTemplateSpecializationType>(Deduced)) {
11964  assert(VDecl && "non-auto type for init capture deduction?");
11967  VDecl->getLocation(), DirectInit, Init);
11968  // FIXME: Initialization should not be taking a mutable list of inits.
11969  SmallVector<Expr*, 8> InitsCopy(DeduceInits.begin(), DeduceInits.end());
11970  return DeduceTemplateSpecializationFromInitializer(TSI, Entity, Kind,
11971  InitsCopy);
11972  }
11973 
11974  if (DirectInit) {
11975  if (auto *IL = dyn_cast<InitListExpr>(Init))
11976  DeduceInits = IL->inits();
11977  }
11978 
11979  // Deduction only works if we have exactly one source expression.
11980  if (DeduceInits.empty()) {
11981  // It isn't possible to write this directly, but it is possible to
11982  // end up in this situation with "auto x(some_pack...);"
11983  Diag(Init->getBeginLoc(), IsInitCapture
11984  ? diag::err_init_capture_no_expression
11985  : diag::err_auto_var_init_no_expression)
11986  << VN << Type << Range;
11987  return QualType();
11988  }
11989 
11990  if (DeduceInits.size() > 1) {
11991  Diag(DeduceInits[1]->getBeginLoc(),
11992  IsInitCapture ? diag::err_init_capture_multiple_expressions
11993  : diag::err_auto_var_init_multiple_expressions)
11994  << VN << Type << Range;
11995  return QualType();
11996  }
11997 
11998  Expr *DeduceInit = DeduceInits[0];
11999  if (DirectInit && isa<InitListExpr>(DeduceInit)) {
12000  Diag(Init->getBeginLoc(), IsInitCapture
12001  ? diag::err_init_capture_paren_braces
12002  : diag::err_auto_var_init_paren_braces)
12003  << isa<InitListExpr>(Init) << VN << Type << Range;
12004  return QualType();
12005  }
12006 
12007  // Expressions default to 'id' when we're in a debugger.
12008  bool DefaultedAnyToId = false;
12009  if (getLangOpts().DebuggerCastResultToId &&
12010  Init->getType() == Context.UnknownAnyTy && !IsInitCapture) {
12011  ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12012  if (Result.isInvalid()) {
12013  return QualType();
12014  }
12015  Init = Result.get();
12016  DefaultedAnyToId = true;
12017  }
12018 
12019  // C++ [dcl.decomp]p1:
12020  // If the assignment-expression [...] has array type A and no ref-qualifier
12021  // is present, e has type cv A
12022  if (VDecl && isa<DecompositionDecl>(VDecl) &&
12023  Context.hasSameUnqualifiedType(Type, Context.getAutoDeductType()) &&
12024  DeduceInit->getType()->isConstantArrayType())
12025  return Context.getQualifiedType(DeduceInit->getType(),
12026  Type.getQualifiers());
12027 
12029  if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
12030  if (!IsInitCapture)
12031  DiagnoseAutoDeductionFailure(VDecl, DeduceInit);
12032  else if (isa<InitListExpr>(Init))
12033  Diag(Range.getBegin(),
12034  diag::err_init_capture_deduction_failure_from_init_list)
12035  << VN
12036  << (DeduceInit->getType().isNull() ? TSI->getType()
12037  : DeduceInit->getType())
12038  << DeduceInit->getSourceRange();
12039  else
12040  Diag(Range.getBegin(), diag::err_init_capture_deduction_failure)
12041  << VN << TSI->getType()
12042  << (DeduceInit->getType().isNull() ? TSI->getType()
12043  : DeduceInit->getType())
12044  << DeduceInit->getSourceRange();
12045  }
12046 
12047  // Warn if we deduced 'id'. 'auto' usually implies type-safety, but using
12048  // 'id' instead of a specific object type prevents most of our usual
12049  // checks.
12050  // We only want to warn outside of template instantiations, though:
12051  // inside a template, the 'id' could have come from a parameter.
12052  if (!inTemplateInstantiation() && !DefaultedAnyToId && !IsInitCapture &&
12053  !DeducedType.isNull() && DeducedType->isObjCIdType()) {
12054  SourceLocation Loc = TSI->getTypeLoc().getBeginLoc();
12055  Diag(Loc, diag::warn_auto_var_is_id) << VN << Range;
12056  }
12057 
12058  return DeducedType;
12059 }
12060 
12061 bool Sema::DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit,
12062  Expr *Init) {
12063  assert(!Init || !Init->containsErrors());
12064  QualType DeducedType = deduceVarTypeFromInitializer(
12065  VDecl, VDecl->getDeclName(), VDecl->getType(), VDecl->getTypeSourceInfo(),
12066  VDecl->getSourceRange(), DirectInit, Init);
12067  if (DeducedType.isNull()) {
12068  VDecl->setInvalidDecl();
12069  return true;
12070  }
12071 
12072  VDecl->setType(DeducedType);
12073  assert(VDecl->isLinkageValid());
12074 
12075  // In ARC, infer lifetime.
12076  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(VDecl))
12077  VDecl->setInvalidDecl();
12078 
12079  if (getLangOpts().OpenCL)
12080  deduceOpenCLAddressSpace(VDecl);
12081 
12082  // If this is a redeclaration, check that the type we just deduced matches
12083  // the previously declared type.
12084  if (VarDecl *Old = VDecl->getPreviousDecl()) {
12085  // We never need to merge the type, because we cannot form an incomplete
12086  // array of auto, nor deduce such a type.
12087  MergeVarDeclTypes(VDecl, Old, /*MergeTypeWithPrevious*/ false);
12088  }
12089 
12090  // Check the deduced type is valid for a variable declaration.
12091  CheckVariableDeclarationType(VDecl);
12092  return VDecl->isInvalidDecl();
12093 }
12094 
12096  SourceLocation Loc) {
12097  if (auto *EWC = dyn_cast<ExprWithCleanups>(Init))
12098  Init = EWC->getSubExpr();
12099 
12100  if (auto *CE = dyn_cast<ConstantExpr>(Init))
12101  Init = CE->getSubExpr();
12102 
12103  QualType InitType = Init->getType();
12105  InitType.hasNonTrivialToPrimitiveCopyCUnion()) &&
12106  "shouldn't be called if type doesn't have a non-trivial C struct");
12107  if (auto *ILE = dyn_cast<InitListExpr>(Init)) {
12108  for (auto I : ILE->inits()) {
12109  if (!I->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion() &&
12110  !I->getType().hasNonTrivialToPrimitiveCopyCUnion())
12111  continue;
12112  SourceLocation SL = I->getExprLoc();
12113  checkNonTrivialCUnionInInitializer(I, SL.isValid() ? SL : Loc);
12114  }
12115  return;
12116  }
12117 
12118  if (isa<ImplicitValueInitExpr>(Init)) {
12120  checkNonTrivialCUnion(InitType, Loc, NTCUC_DefaultInitializedObject,
12121  NTCUK_Init);
12122  } else {
12123  // Assume all other explicit initializers involving copying some existing
12124  // object.
12125  // TODO: ignore any explicit initializers where we can guarantee
12126  // copy-elision.
12127  if (InitType.hasNonTrivialToPrimitiveCopyCUnion())
12128  checkNonTrivialCUnion(InitType, Loc, NTCUC_CopyInit, NTCUK_Copy);
12129  }
12130 }
12131 
12132 namespace {
12133 
12134 bool shouldIgnoreForRecordTriviality(const FieldDecl *FD) {
12135  // Ignore unavailable fields. A field can be marked as unavailable explicitly
12136  // in the source code or implicitly by the compiler if it is in a union
12137  // defined in a system header and has non-trivial ObjC ownership
12138  // qualifications. We don't want those fields to participate in determining
12139  // whether the containing union is non-trivial.
12140  return FD->hasAttr<UnavailableAttr>();
12141 }
12142 
12143 struct DiagNonTrivalCUnionDefaultInitializeVisitor
12144  : DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12145  void> {
12146  using Super =
12147  DefaultInitializedTypeVisitor<DiagNonTrivalCUnionDefaultInitializeVisitor,
12148  void>;
12149 
12150  DiagNonTrivalCUnionDefaultInitializeVisitor(
12151  QualType OrigTy, SourceLocation OrigLoc,
12152  Sema::NonTrivialCUnionContext UseContext, Sema &S)
12153  : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12154 
12155  void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType QT,
12156  const FieldDecl *FD, bool InNonTrivialUnion) {
12157  if (const auto *AT = S.Context.getAsArrayType(QT))
12158  return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12159  InNonTrivialUnion);
12160  return Super::visitWithKind(PDIK, QT, FD, InNonTrivialUnion);
12161  }
12162 
12163  void visitARCStrong(QualType QT, const FieldDecl *FD,
12164  bool InNonTrivialUnion) {
12165  if (InNonTrivialUnion)
12166  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12167  << 1 << 0 << QT << FD->getName();
12168  }
12169 
12170  void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12171  if (InNonTrivialUnion)
12172  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12173  << 1 << 0 << QT << FD->getName();
12174  }
12175 
12176  void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12177  const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12178  if (RD->isUnion()) {
12179  if (OrigLoc.isValid()) {
12180  bool IsUnion = false;
12181  if (auto *OrigRD = OrigTy->getAsRecordDecl())
12182  IsUnion = OrigRD->isUnion();
12183  S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12184  << 0 << OrigTy << IsUnion << UseContext;
12185  // Reset OrigLoc so that this diagnostic is emitted only once.
12186  OrigLoc = SourceLocation();
12187  }
12188  InNonTrivialUnion = true;
12189  }
12190 
12191  if (InNonTrivialUnion)
12192  S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12193  << 0 << 0 << QT.getUnqualifiedType() << "";
12194 
12195  for (const FieldDecl *FD : RD->fields())
12196  if (!shouldIgnoreForRecordTriviality(FD))
12197  asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12198  }
12199 
12200  void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12201 
12202  // The non-trivial C union type or the struct/union type that contains a
12203  // non-trivial C union.
12204  QualType OrigTy;
12205  SourceLocation OrigLoc;
12206  Sema::NonTrivialCUnionContext UseContext;
12207  Sema &S;
12208 };
12209 
12210 struct DiagNonTrivalCUnionDestructedTypeVisitor
12211  : DestructedTypeVisitor<DiagNonTrivalCUnionDestructedTypeVisitor, void> {
12212  using Super =
12214 
12215  DiagNonTrivalCUnionDestructedTypeVisitor(
12216  QualType OrigTy, SourceLocation OrigLoc,
12217  Sema::NonTrivialCUnionContext UseContext, Sema &S)
12218  : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12219 
12220  void visitWithKind(QualType::DestructionKind DK, QualType QT,
12221  const FieldDecl *FD, bool InNonTrivialUnion) {
12222  if (const auto *AT = S.Context.getAsArrayType(QT))
12223  return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12224  InNonTrivialUnion);
12225  return Super::visitWithKind(DK, QT, FD, InNonTrivialUnion);
12226  }
12227 
12228  void visitARCStrong(QualType QT, const FieldDecl *FD,
12229  bool InNonTrivialUnion) {
12230  if (InNonTrivialUnion)
12231  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12232  << 1 << 1 << QT << FD->getName();
12233  }
12234 
12235  void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12236  if (InNonTrivialUnion)
12237  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12238  << 1 << 1 << QT << FD->getName();
12239  }
12240 
12241  void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12242  const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12243  if (RD->isUnion()) {
12244  if (OrigLoc.isValid()) {
12245  bool IsUnion = false;
12246  if (auto *OrigRD = OrigTy->getAsRecordDecl())
12247  IsUnion = OrigRD->isUnion();
12248  S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12249  << 1 << OrigTy << IsUnion << UseContext;
12250  // Reset OrigLoc so that this diagnostic is emitted only once.
12251  OrigLoc = SourceLocation();
12252  }
12253  InNonTrivialUnion = true;
12254  }
12255 
12256  if (InNonTrivialUnion)
12257  S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12258  << 0 << 1 << QT.getUnqualifiedType() << "";
12259 
12260  for (const FieldDecl *FD : RD->fields())
12261  if (!shouldIgnoreForRecordTriviality(FD))
12262  asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12263  }
12264 
12265  void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12266  void visitCXXDestructor(QualType QT, const FieldDecl *FD,
12267  bool InNonTrivialUnion) {}
12268 
12269  // The non-trivial C union type or the struct/union type that contains a
12270  // non-trivial C union.
12271  QualType OrigTy;
12272  SourceLocation OrigLoc;
12273  Sema::NonTrivialCUnionContext UseContext;
12274  Sema &S;
12275 };
12276 
12277 struct DiagNonTrivalCUnionCopyVisitor
12278  : CopiedTypeVisitor<DiagNonTrivalCUnionCopyVisitor, false, void> {
12280 
12281  DiagNonTrivalCUnionCopyVisitor(QualType OrigTy, SourceLocation OrigLoc,
12282  Sema::NonTrivialCUnionContext UseContext,
12283  Sema &S)
12284  : OrigTy(OrigTy), OrigLoc(OrigLoc), UseContext(UseContext), S(S) {}
12285 
12286  void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType QT,
12287  const FieldDecl *FD, bool InNonTrivialUnion) {
12288  if (const auto *AT = S.Context.getAsArrayType(QT))
12289  return this->asDerived().visit(S.Context.getBaseElementType(AT), FD,
12290  InNonTrivialUnion);
12291  return Super::visitWithKind(PCK, QT, FD, InNonTrivialUnion);
12292  }
12293 
12294  void visitARCStrong(QualType QT, const FieldDecl *FD,
12295  bool InNonTrivialUnion) {
12296  if (InNonTrivialUnion)
12297  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12298  << 1 << 2 << QT << FD->getName();
12299  }
12300 
12301  void visitARCWeak(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12302  if (InNonTrivialUnion)
12303  S.Diag(FD->getLocation(), diag::note_non_trivial_c_union)
12304  << 1 << 2 << QT << FD->getName();
12305  }
12306 
12307  void visitStruct(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {
12308  const RecordDecl *RD = QT->castAs<RecordType>()->getDecl();
12309  if (RD->isUnion()) {
12310  if (OrigLoc.isValid()) {
12311  bool IsUnion = false;
12312  if (auto *OrigRD = OrigTy->getAsRecordDecl())
12313  IsUnion = OrigRD->isUnion();
12314  S.Diag(OrigLoc, diag::err_non_trivial_c_union_in_invalid_context)
12315  << 2 << OrigTy << IsUnion << UseContext;
12316  // Reset OrigLoc so that this diagnostic is emitted only once.
12317  OrigLoc = SourceLocation();
12318  }
12319  InNonTrivialUnion = true;
12320  }
12321 
12322  if (InNonTrivialUnion)
12323  S.Diag(RD->getLocation(), diag::note_non_trivial_c_union)
12324  << 0 << 2 << QT.getUnqualifiedType() << "";
12325 
12326  for (const FieldDecl *FD : RD->fields())
12327  if (!shouldIgnoreForRecordTriviality(FD))
12328  asDerived().visit(FD->getType(), FD, InNonTrivialUnion);
12329  }
12330 
12331  void preVisit(QualType::PrimitiveCopyKind PCK, QualType QT,
12332  const FieldDecl *FD, bool InNonTrivialUnion) {}
12333  void visitTrivial(QualType QT, const FieldDecl *FD, bool InNonTrivialUnion) {}
12334  void visitVolatileTrivial(QualType QT, const FieldDecl *FD,
12335  bool InNonTrivialUnion) {}
12336 
12337  // The non-trivial C union type or the struct/union type that contains a
12338  // non-trivial C union.
12339  QualType OrigTy;
12340  SourceLocation OrigLoc;
12341  Sema::NonTrivialCUnionContext UseContext;
12342  Sema &S;
12343 };
12344 
12345 } // namespace
12346 
12348  NonTrivialCUnionContext UseContext,
12349  unsigned NonTrivialKind) {
12353  "shouldn't be called if type doesn't have a non-trivial C union");
12354 
12355  if ((NonTrivialKind & NTCUK_Init) &&
12357  DiagNonTrivalCUnionDefaultInitializeVisitor(QT, Loc, UseContext, *this)
12358  .visit(QT, nullptr, false);
12359  if ((NonTrivialKind & NTCUK_Destruct) &&
12361  DiagNonTrivalCUnionDestructedTypeVisitor(QT, Loc, UseContext, *this)
12362  .visit(QT, nullptr, false);
12363  if ((NonTrivialKind & NTCUK_Copy) && QT.hasNonTrivialToPrimitiveCopyCUnion())
12364  DiagNonTrivalCUnionCopyVisitor(QT, Loc, UseContext, *this)
12365  .visit(QT, nullptr, false);
12366 }
12367 
12368 /// AddInitializerToDecl - Adds the initializer Init to the
12369 /// declaration dcl. If DirectInit is true, this is C++ direct
12370 /// initialization rather than copy initialization.
12371 void Sema::AddInitializerToDecl(Decl *RealDecl, Expr *Init, bool DirectInit) {
12372  // If there is no declaration, there was an error parsing it. Just ignore
12373  // the initializer.
12374  if (!RealDecl || RealDecl->isInvalidDecl()) {
12375  CorrectDelayedTyposInExpr(Init, dyn_cast_or_null<VarDecl>(RealDecl));
12376  return;
12377  }
12378 
12379  if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
12380  // Pure-specifiers are handled in ActOnPureSpecifier.
12381  Diag(Method->getLocation(), diag::err_member_function_initialization)
12382  << Method->getDeclName() << Init->getSourceRange();
12383  Method->setInvalidDecl();
12384  return;
12385  }
12386 
12387  VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
12388  if (!VDecl) {
12389  assert(!isa<FieldDecl>(RealDecl) && "field init shouldn't get here");
12390  Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
12391  RealDecl->setInvalidDecl();
12392  return;
12393  }
12394 
12395  // C++11 [decl.spec.auto]p6. Deduce the type which 'auto' stands in for.
12396  if (VDecl->getType()->isUndeducedType()) {
12397  // Attempt typo correction early so that the type of the init expression can
12398  // be deduced based on the chosen correction if the original init contains a
12399  // TypoExpr.
12400  ExprResult Res = CorrectDelayedTyposInExpr(Init, VDecl);
12401  if (!Res.isUsable()) {
12402  // There are unresolved typos in Init, just drop them.
12403  // FIXME: improve the recovery strategy to preserve the Init.
12404  RealDecl->setInvalidDecl();
12405  return;
12406  }
12407  if (Res.get()->containsErrors()) {
12408  // Invalidate the decl as we don't know the type for recovery-expr yet.
12409  RealDecl->setInvalidDecl();
12410  VDecl->setInit(Res.get());
12411  return;
12412  }
12413  Init = Res.get();
12414 
12415  if (DeduceVariableDeclarationType(VDecl, DirectInit, Init))
12416  return;
12417  }
12418 
12419  // dllimport cannot be used on variable definitions.
12420  if (VDecl->hasAttr<DLLImportAttr>() && !VDecl->isStaticDataMember()) {
12421  Diag(VDecl->getLocation(), diag::err_attribute_dllimport_data_definition);
12422  VDecl->setInvalidDecl();
12423  return;
12424  }
12425 
12426  if (VDecl->isLocalVarDecl() && VDecl->hasExternalStorage()) {
12427  // C99 6.7.8p5. C++ has no such restriction, but that is a defect.
12428  Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
12429  VDecl->setInvalidDecl();
12430  return;
12431  }
12432 
12433  if (!VDecl->getType()->isDependentType()) {
12434  // A definition must end up with a complete type, which means it must be
12435  // complete with the restriction that an array type might be completed by
12436  // the initializer; note that later code assumes this restriction.
12437  QualType BaseDeclType = VDecl->getType();
12438  if (const ArrayType *Array = Context.getAsIncompleteArrayType(BaseDeclType))
12439  BaseDeclType = Array->getElementType();
12440  if (RequireCompleteType(VDecl->getLocation(), BaseDeclType,
12441  diag::err_typecheck_decl_incomplete_type)) {
12442  RealDecl->setInvalidDecl();
12443  return;
12444  }
12445 
12446  // The variable can not have an abstract class type.
12447  if (RequireNonAbstractType(VDecl->getLocation(), VDecl->getType(),
12448  diag::err_abstract_type_in_decl,
12449  AbstractVariableType))
12450  VDecl->setInvalidDecl();
12451  }
12452 
12453  // If adding the initializer will turn this declaration into a definition,
12454  // and we already have a definition for this variable, diagnose or otherwise
12455  // handle the situation.
12456  if (VarDecl *Def = VDecl->getDefinition())
12457  if (Def != VDecl &&
12458  (!VDecl->isStaticDataMember() || VDecl->isOutOfLine()) &&
12460  checkVarDeclRedefinition(Def, VDecl))
12461  return;
12462 
12463  if (getLangOpts().CPlusPlus) {
12464  // C++ [class.static.data]p4
12465  // If a static data member is of const integral or const
12466  // enumeration type, its declaration in the class definition can
12467  // specify a constant-initializer which shall be an integral
12468  // constant expression (5.19). In that case, the member can appear
12469  // in integral constant expressions. The member shall still be
12470  // defined in a namespace scope if it is used in the program and the
12471  // namespace scope definition shall not contain an initializer.
12472  //
12473  // We already performed a redefinition check above, but for static
12474  // data members we also need to check whether there was an in-class
12475  // declaration with an initializer.
12476  if (VDecl->isStaticDataMember() && VDecl->getCanonicalDecl()->hasInit()) {
12477  Diag(Init->getExprLoc(), diag::err_static_data_member_reinitialization)
12478  << VDecl->getDeclName();
12479  Diag(VDecl->getCanonicalDecl()->getInit()->getExprLoc(),
12480  diag::note_previous_initializer)
12481  << 0;
12482  return;
12483  }
12484 
12485  if (VDecl->hasLocalStorage())
12486  setFunctionHasBranchProtectedScope();
12487 
12488  if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer)) {
12489  VDecl->setInvalidDecl();
12490  return;
12491  }
12492  }
12493 
12494  // OpenCL 1.1 6.5.2: "Variables allocated in the __local address space inside
12495  // a kernel function cannot be initialized."
12496  if (VDecl->getType().getAddressSpace() == LangAS::opencl_local) {
12497  Diag(VDecl->getLocation(), diag::err_local_cant_init);
12498  VDecl->setInvalidDecl();
12499  return;
12500  }
12501  // In the SYCL explicit SIMD extension non constant "private globals" can't
12502  // be explicitly initialized in the declaration.
12503  if (isSYCLEsimdPrivateGlobal(VDecl)) {
12504  Diag(VDecl->getLocation(), diag::err_esimd_glob_cant_init);
12505  VDecl->setInvalidDecl();
12506  return;
12507  }
12508 
12509  // The LoaderUninitialized attribute acts as a definition (of undef).
12510  if (VDecl->hasAttr<LoaderUninitializedAttr>()) {
12511  Diag(VDecl->getLocation(), diag::err_loader_uninitialized_cant_init);
12512  VDecl->setInvalidDecl();
12513  return;
12514  }
12515 
12516  // Get the decls type and save a reference for later, since
12517  // CheckInitializerTypes may change it.
12518  QualType DclT = VDecl->getType(), SavT = DclT;
12519 
12520  // Expressions default to 'id' when we're in a debugger
12521  // and we are assigning it to a variable of Objective-C pointer type.
12522  if (getLangOpts().DebuggerCastResultToId && DclT->isObjCObjectPointerType() &&
12523  Init->getType() == Context.UnknownAnyTy) {
12524  ExprResult Result = forceUnknownAnyToType(Init, Context.getObjCIdType());
12525  if (Result.isInvalid()) {
12526  VDecl->setInvalidDecl();
12527  return;
12528  }
12529  Init = Result.get();
12530  }
12531 
12532  // Perform the initialization.
12533  ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
12534  if (!VDecl->isInvalidDecl()) {
12537  VDecl->getLocation(), DirectInit, Init);
12538 
12539  MultiExprArg Args = Init;
12540  if (CXXDirectInit)
12541  Args = MultiExprArg(CXXDirectInit->getExprs(),
12542  CXXDirectInit->getNumExprs());
12543 
12544  // Try to correct any TypoExprs in the initialization arguments.
12545  for (size_t Idx = 0; Idx < Args.size(); ++Idx) {
12546  ExprResult Res = CorrectDelayedTyposInExpr(
12547  Args[Idx], VDecl, /*RecoverUncorrectedTypos=*/true,
12548  [this, Entity, Kind](Expr *E) {
12549  InitializationSequence Init(*this, Entity, Kind, MultiExprArg(E));
12550  return Init.Failed() ? ExprError() : E;
12551  });
12552  if (Res.isInvalid()) {
12553  VDecl->setInvalidDecl();
12554  } else if (Res.get() != Args[Idx]) {
12555  Args[Idx] = Res.get();
12556  }
12557  }
12558  if (VDecl->isInvalidDecl())
12559  return;
12560 
12561  InitializationSequence InitSeq(*this, Entity, Kind, Args,
12562  /*TopLevelOfInitList=*/false,
12563  /*TreatUnavailableAsInvalid=*/false);
12564  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
12565  if (Result.isInvalid()) {
12566  // If the provided initializer fails to initialize the var decl,
12567  // we attach a recovery expr for better recovery.
12568  auto RecoveryExpr =
12569  CreateRecoveryExpr(Init->getBeginLoc(), Init->getEndLoc(), Args);
12570  if (RecoveryExpr.get())
12571  VDecl->setInit(RecoveryExpr.get());
12572  return;
12573  }
12574 
12575  Init = Result.getAs<Expr>();
12576  }
12577 
12578  // Check for self-references within variable initializers.
12579  // Variables declared within a function/method body (except for references)
12580  // are handled by a dataflow analysis.
12581  // This is undefined behavior in C++, but valid in C.
12582  if (getLangOpts().CPlusPlus)
12583  if (!VDecl->hasLocalStorage() || VDecl->getType()->isRecordType() ||
12584  VDecl->getType()->isReferenceType())
12585  CheckSelfReference(*this, RealDecl, Init, DirectInit);
12586 
12587  // If the type changed, it means we had an incomplete type that was
12588  // completed by the initializer. For example:
12589  // int ary[] = { 1, 3, 5 };
12590  // "ary" transitions from an IncompleteArrayType to a ConstantArrayType.
12591  if (!VDecl->isInvalidDecl() && (DclT != SavT))
12592  VDecl->setType(DclT);
12593 
12594  if (!VDecl->isInvalidDecl()) {
12595  checkUnsafeAssigns(VDecl->getLocation(), VDecl->getType(), Init);
12596 
12597  if (VDecl->hasAttr<BlocksAttr>())
12598  checkRetainCycles(VDecl, Init);
12599 
12600  // It is safe to assign a weak reference into a strong variable.
12601  // Although this code can still have problems:
12602  // id x = self.weakProp;
12603  // id y = self.weakProp;
12604  // we do not warn to warn spuriously when 'x' and 'y' are on separate
12605  // paths through the function. This should be revisited if
12606  // -Wrepeated-use-of-weak is made flow-sensitive.
12607  if (FunctionScopeInfo *FSI = getCurFunction())
12608  if ((VDecl->getType().getObjCLifetime() == Qualifiers::OCL_Strong ||
12609  VDecl->getType().isNonWeakInMRRWithObjCWeak(Context)) &&
12610  !Diags.isIgnored(diag::warn_arc_repeated_use_of_weak,
12611  Init->getBeginLoc()))
12612  FSI->markSafeWeakUse(Init);
12613  }
12614 
12615  // The initialization is usually a full-expression.
12616  //
12617  // FIXME: If this is a braced initialization of an aggregate, it is not
12618  // an expression, and each individual field initializer is a separate
12619  // full-expression. For instance, in:
12620  //
12621  // struct Temp { ~Temp(); };
12622  // struct S { S(Temp); };
12623  // struct T { S a, b; } t = { Temp(), Temp() }
12624  //
12625  // we should destroy the first Temp before constructing the second.
12626  ExprResult Result =
12627  ActOnFinishFullExpr(Init, VDecl->getLocation(),
12628  /*DiscardedValue*/ false, VDecl->isConstexpr());
12629  if (Result.isInvalid()) {
12630  VDecl->setInvalidDecl();
12631  return;
12632  }
12633  Init = Result.get();
12634 
12635  // Attach the initializer to the decl.
12636  VDecl->setInit(Init);
12637 
12638  if (VDecl->isLocalVarDecl()) {
12639  // Don't check the initializer if the declaration is malformed.
12640  if (VDecl->isInvalidDecl()) {
12641  // do nothing
12642 
12643  // OpenCL v1.2 s6.5.3: __constant locals must be constant-initialized.
12644  // This is true even in C++ for OpenCL.
12645  } else if (VDecl->getType().getAddressSpace() == LangAS::opencl_constant) {
12646  CheckForConstantInitializer(Init, DclT);
12647 
12648  // Otherwise, C++ does not restrict the initializer.
12649  } else if (getLangOpts().CPlusPlus) {
12650  // do nothing
12651 
12652  // C99 6.7.8p4: All the expressions in an initializer for an object that has
12653  // static storage duration shall be constant expressions or string literals.
12654  } else if (VDecl->getStorageClass() == SC_Static) {
12655  CheckForConstantInitializer(Init, DclT);
12656 
12657  // C89 is stricter than C99 for aggregate initializers.
12658  // C89 6.5.7p3: All the expressions [...] in an initializer list
12659  // for an object that has aggregate or union type shall be
12660  // constant expressions.
12661  } else if (!getLangOpts().C99 && VDecl->getType()->isAggregateType() &&
12662  isa<InitListExpr>(Init)) {
12663  const Expr *Culprit;
12664  if (!Init->isConstantInitializer(Context, false, &Culprit)) {
12665  Diag(Culprit->getExprLoc(),
12666  diag::ext_aggregate_init_not_constant)
12667  << Culprit->getSourceRange();
12668  }
12669  }
12670 
12671  if (auto *E = dyn_cast<ExprWithCleanups>(Init))
12672  if (auto *BE = dyn_cast<BlockExpr>(E->getSubExpr()->IgnoreParens()))
12673  if (VDecl->hasLocalStorage())
12674  BE->getBlockDecl()->setCanAvoidCopyToHeap();
12675  } else if (VDecl->isStaticDataMember() && !VDecl->isInline() &&
12676  VDecl->getLexicalDeclContext()->isRecord()) {
12677  // This is an in-class initialization for a static data member, e.g.,
12678  //
12679  // struct S {
12680  // static const int value = 17;
12681  // };
12682 
12683  // C++ [class.mem]p4:
12684  // A member-declarator can contain a constant-initializer only
12685  // if it declares a static member (9.4) of const integral or
12686  // const enumeration type, see 9.4.2.
12687  //
12688  // C++11 [class.static.data]p3:
12689  // If a non-volatile non-inline const static data member is of integral
12690  // or enumeration type, its declaration in the class definition can
12691  // specify a brace-or-equal-initializer in which every initializer-clause
12692  // that is an assignment-expression is a constant expression. A static
12693  // data member of literal type can be declared in the class definition
12694  // with the constexpr specifier; if so, its declaration shall specify a
12695  // brace-or-equal-initializer in which every initializer-clause that is
12696  // an assignment-expression is a constant expression.
12697 
12698  // Do nothing on dependent types.
12699  if (DclT->isDependentType()) {
12700 
12701  // Allow any 'static constexpr' members, whether or not they are of literal
12702  // type. We separately check that every constexpr variable is of literal
12703  // type.
12704  } else if (VDecl->isConstexpr()) {
12705 
12706  // Require constness.
12707  } else if (!DclT.isConstQualified()) {
12708  Diag(VDecl->getLocation(), diag::err_in_class_initializer_non_const)
12709  << Init->getSourceRange();
12710  VDecl->setInvalidDecl();
12711 
12712  // We allow integer constant expressions in all cases.
12713  } else if (DclT->isIntegralOrEnumerationType()) {
12714  // Check whether the expression is a constant expression.
12715  SourceLocation Loc;
12716  if (getLangOpts().CPlusPlus11 && DclT.isVolatileQualified())
12717  // In C++11, a non-constexpr const static data member with an
12718  // in-class initializer cannot be volatile.
12719  Diag(VDecl->getLocation(), diag::err_in_class_initializer_volatile);
12720  else if (Init->isValueDependent())
12721  ; // Nothing to check.
12722  else if (Init->isIntegerConstantExpr(Context, &Loc))
12723  ; // Ok, it's an ICE!
12724  else if (Init->getType()->isScopedEnumeralType() &&
12725  Init->isCXX11ConstantExpr(Context))
12726  ; // Ok, it is a scoped-enum constant expression.
12727  else if (Init->isEvaluatable(Context)) {
12728  // If we can constant fold the initializer through heroics, accept it,
12729  // but report this as a use of an extension for -pedantic.
12730  Diag(Loc, diag::ext_in_class_initializer_non_constant)
12731  << Init->getSourceRange();
12732  } else {
12733  // Otherwise, this is some crazy unknown case. Report the issue at the
12734  // location provided by the isIntegerConstantExpr failed check.
12735  Diag(Loc, diag::err_in_class_initializer_non_constant)
12736  << Init->getSourceRange();
12737  VDecl->setInvalidDecl();
12738  }
12739 
12740  // We allow foldable floating-point constants as an extension.
12741  } else if (DclT->isFloatingType()) { // also permits complex, which is ok
12742  // In C++98, this is a GNU extension. In C++11, it is not, but we support
12743  // it anyway and provide a fixit to add the 'constexpr'.
12744  if (getLangOpts().CPlusPlus11) {
12745  Diag(VDecl->getLocation(),
12746  diag::ext_in_class_initializer_float_type_cxx11)
12747  << DclT << Init->getSourceRange();
12748  Diag(VDecl->getBeginLoc(),
12749  diag::note_in_class_initializer_float_type_cxx11)
12750  << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12751  } else {
12752  Diag(VDecl->getLocation(), diag::ext_in_class_initializer_float_type)
12753  << DclT << Init->getSourceRange();
12754 
12755  if (!Init->isValueDependent() && !Init->isEvaluatable(Context)) {
12756  Diag(Init->getExprLoc(), diag::err_in_class_initializer_non_constant)
12757  << Init->getSourceRange();
12758  VDecl->setInvalidDecl();
12759  }
12760  }
12761 
12762  // Suggest adding 'constexpr' in C++11 for literal types.
12763  } else if (getLangOpts().CPlusPlus11 && DclT->isLiteralType(Context)) {
12764  Diag(VDecl->getLocation(), diag::err_in_class_initializer_literal_type)
12765  << DclT << Init->getSourceRange()
12766  << FixItHint::CreateInsertion(VDecl->getBeginLoc(), "constexpr ");
12767  VDecl->setConstexpr(true);
12768 
12769  } else {
12770  Diag(VDecl->getLocation(), diag::err_in_class_initializer_bad_type)
12771  << DclT << Init->getSourceRange();
12772  VDecl->setInvalidDecl();
12773  }
12774  } else if (VDecl->isFileVarDecl()) {
12775  // In C, extern is typically used to avoid tentative definitions when
12776  // declaring variables in headers, but adding an intializer makes it a
12777  // definition. This is somewhat confusing, so GCC and Clang both warn on it.
12778  // In C++, extern is often used to give implictly static const variables
12779  // external linkage, so don't warn in that case. If selectany is present,
12780  // this might be header code intended for C and C++ inclusion, so apply the
12781  // C++ rules.
12782  if (VDecl->getStorageClass() == SC_Extern &&
12783  ((!getLangOpts().CPlusPlus && !VDecl->hasAttr<SelectAnyAttr>()) ||
12784  !Context.getBaseElementType(VDecl->getType()).isConstQualified()) &&
12785  !(getLangOpts().CPlusPlus && VDecl->isExternC()) &&
12787  Diag(VDecl->getLocation(), diag::warn_extern_init);
12788 
12789  // In Microsoft C++ mode, a const variable defined in namespace scope has
12790  // external linkage by default if the variable is declared with
12791  // __declspec(dllexport).
12792  if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
12793  getLangOpts().CPlusPlus && VDecl->getType().isConstQualified() &&
12794  VDecl->hasAttr<DLLExportAttr>() && VDecl->getDefinition())
12795  VDecl->setStorageClass(SC_Extern);
12796 
12797  // C99 6.7.8p4. All file scoped initializers need to be constant.
12798  if (!getLangOpts().CPlusPlus && !VDecl->isInvalidDecl())
12799  CheckForConstantInitializer(Init, DclT);
12800  }
12801 
12802  QualType InitType = Init->getType();
12803  if (!InitType.isNull() &&
12806  checkNonTrivialCUnionInInitializer(Init, Init->getExprLoc());
12807 
12808  // We will represent direct-initialization similarly to copy-initialization:
12809  // int x(1); -as-> int x = 1;
12810  // ClassType x(a,b,c); -as-> ClassType x = ClassType(a,b,c);
12811  //
12812  // Clients that want to distinguish between the two forms, can check for
12813  // direct initializer using VarDecl::getInitStyle().
12814  // A major benefit is that clients that don't particularly care about which
12815  // exactly form was it (like the CodeGen) can handle both cases without
12816  // special case code.
12817 
12818  // C++ 8.5p11:
12819  // The form of initialization (using parentheses or '=') is generally
12820  // insignificant, but does matter when the entity being initialized has a
12821  // class type.
12822  if (CXXDirectInit) {
12823  assert(DirectInit && "Call-style initializer must be direct init.");
12825  } else if (DirectInit) {
12826  // This must be list-initialization. No other way is direct-initialization.
12828  }
12829 
12830  if (LangOpts.OpenMP &&
12831  (LangOpts.OpenMPIsDevice || !LangOpts.OMPTargetTriples.empty()) &&
12832  VDecl->isFileVarDecl())
12833  DeclsToCheckForDeferredDiags.insert(VDecl);
12834  CheckCompleteVariableDeclaration(VDecl);
12835 }
12836 
12837 /// ActOnInitializerError - Given that there was an error parsing an
12838 /// initializer for the given declaration, try to at least re-establish
12839 /// invariants such as whether a variable's type is either dependent or
12840 /// complete.
12842  // Our main concern here is re-establishing invariants like "a
12843  // variable's type is either dependent or complete".
12844  if (!D || D->isInvalidDecl()) return;
12845 
12846  VarDecl *VD = dyn_cast<VarDecl>(D);
12847  if (!VD) return;
12848 
12849  // Bindings are not usable if we can't make sense of the initializer.
12850  if (auto *DD = dyn_cast<DecompositionDecl>(D))
12851  for (auto *BD : DD->bindings())
12852  BD->setInvalidDecl();
12853 
12854  // Auto types are meaningless if we can't make sense of the initializer.
12855  if (VD->getType()->isUndeducedType()) {
12856  D->setInvalidDecl();
12857  return;
12858  }
12859 
12860  QualType Ty = VD->getType();
12861  if (Ty->isDependentType()) return;
12862 
12863  // Require a complete type.
12864  if (RequireCompleteType(VD->getLocation(),
12865  Context.getBaseElementType(Ty),
12866  diag::err_typecheck_decl_incomplete_type)) {
12867  VD->setInvalidDecl();
12868  return;
12869  }
12870 
12871  // Require a non-abstract type.
12872  if (RequireNonAbstractType(VD->getLocation(), Ty,
12873  diag::err_abstract_type_in_decl,
12874  AbstractVariableType)) {
12875  VD->setInvalidDecl();
12876  return;
12877  }
12878 
12879  // Don't bother complaining about constructors or destructors,
12880  // though.
12881 }
12882 
12884  // If there is no declaration, there was an error parsing it. Just ignore it.
12885  if (!RealDecl)
12886  return;
12887 
12888  if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
12889  QualType Type = Var->getType();
12890 
12891  // C++1z [dcl.dcl]p1 grammar implies that an initializer is mandatory.
12892  if (isa<DecompositionDecl>(RealDecl)) {
12893  Diag(Var->getLocation(), diag::err_decomp_decl_requires_init) << Var;
12894  Var->setInvalidDecl();
12895  return;
12896  }
12897 
12898  if (Type->isUndeducedType() &&
12899  DeduceVariableDeclarationType(Var, false, nullptr))
12900  return;
12901 
12902  // C++11 [class.static.data]p3: A static data member can be declared with
12903  // the constexpr specifier; if so, its declaration shall specify
12904  // a brace-or-equal-initializer.
12905  // C++11 [dcl.constexpr]p1: The constexpr specifier shall be applied only to
12906  // the definition of a variable [...] or the declaration of a static data
12907  // member.
12908  if (Var->isConstexpr() && !Var->isThisDeclarationADefinition() &&
12909  !Var->isThisDeclarationADemotedDefinition()) {
12910  if (Var->isStaticDataMember()) {
12911  // C++1z removes the relevant rule; the in-class declaration is always
12912  // a definition there.
12913  if (!getLangOpts().CPlusPlus17 &&
12914  !Context.getTargetInfo().getCXXABI().isMicrosoft()) {
12915  Diag(Var->getLocation(),
12916  diag::err_constexpr_static_mem_var_requires_init)
12917  << Var;
12918  Var->setInvalidDecl();
12919  return;
12920  }
12921  } else {
12922  Diag(Var->getLocation(), diag::err_invalid_constexpr_var_decl);
12923  Var->setInvalidDecl();
12924  return;
12925  }
12926  }
12927 
12928  // OpenCL v1.1 s6.5.3: variables declared in the constant address space must
12929  // be initialized.
12930  if (!Var->isInvalidDecl() &&
12931  Var->getType().getAddressSpace() == LangAS::opencl_constant &&
12932  Var->getStorageClass() != SC_Extern && !Var->getInit()) {
12933  bool HasConstExprDefaultConstructor = false;
12934  if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12935  for (auto *Ctor : RD->ctors()) {
12936  if (Ctor->isConstexpr() && Ctor->getNumParams() == 0 &&
12937  Ctor->getMethodQualifiers().getAddressSpace() ==
12939  HasConstExprDefaultConstructor = true;
12940  }
12941  }
12942  }
12943  if (!HasConstExprDefaultConstructor) {
12944  Diag(Var->getLocation(), diag::err_opencl_constant_no_init);
12945  Var->setInvalidDecl();
12946  return;
12947  }
12948  }
12949 
12950  if (!Var->isInvalidDecl() && RealDecl->hasAttr<LoaderUninitializedAttr>()) {
12951  if (Var->getStorageClass() == SC_Extern) {
12952  Diag(Var->getLocation(), diag::err_loader_uninitialized_extern_decl)
12953  << Var;
12954  Var->setInvalidDecl();
12955  return;
12956  }
12957  if (RequireCompleteType(Var->getLocation(), Var->getType(),
12958  diag::err_typecheck_decl_incomplete_type)) {
12959  Var->setInvalidDecl();
12960  return;
12961  }
12962  if (CXXRecordDecl *RD = Var->getType()->getAsCXXRecordDecl()) {
12963  if (!RD->hasTrivialDefaultConstructor()) {
12964  Diag(Var->getLocation(), diag::err_loader_uninitialized_trivial_ctor);
12965  Var->setInvalidDecl();
12966  return;
12967  }
12968  }
12969  // The declaration is unitialized, no need for further checks.
12970  return;
12971  }
12972 
12973  VarDecl::DefinitionKind DefKind = Var->isThisDeclarationADefinition();
12974  if (!Var->isInvalidDecl() && DefKind != VarDecl::DeclarationOnly &&
12975  Var->getType().hasNonTrivialToPrimitiveDefaultInitializeCUnion())
12976  checkNonTrivialCUnion(Var->getType(), Var->getLocation(),
12977  NTCUC_DefaultInitializedObject, NTCUK_Init);
12978 
12979 
12980  switch (DefKind) {
12981  case VarDecl::Definition:
12982  if (!Var->isStaticDataMember() || !Var->getAnyInitializer())
12983  break;
12984 
12985  // We have an out-of-line definition of a static data member
12986  // that has an in-class initializer, so we type-check this like
12987  // a declaration.
12988  //
12989  LLVM_FALLTHROUGH;
12990 
12992  // It's only a declaration.
12993 
12994  // Block scope. C99 6.7p7: If an identifier for an object is
12995  // declared with no linkage (C99 6.2.2p6), the type for the
12996  // object shall be complete.
12997  if (!Type->isDependentType() && Var->isLocalVarDecl() &&
12998  !Var->hasLinkage() && !Var->isInvalidDecl() &&
12999  RequireCompleteType(Var->getLocation(), Type,
13000  diag::err_typecheck_decl_incomplete_type))
13001  Var->setInvalidDecl();
13002 
13003  // Make sure that the type is not abstract.
13004  if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13005  RequireNonAbstractType(Var->getLocation(), Type,
13006  diag::err_abstract_type_in_decl,
13007  AbstractVariableType))
13008  Var->setInvalidDecl();
13009  if (!Type->isDependentType() && !Var->isInvalidDecl() &&
13010  Var->getStorageClass() == SC_PrivateExtern) {
13011  Diag(Var->getLocation(), diag::warn_private_extern);
13012  Diag(Var->getLocation(), diag::note_private_extern);
13013  }
13014 
13015  if (Context.getTargetInfo().allowDebugInfoForExternalRef() &&
13016  !Var->isInvalidDecl() && !getLangOpts().CPlusPlus)
13017  ExternalDeclarations.push_back(Var);
13018 
13019  return;
13020 
13022  // File scope. C99 6.9.2p2: A declaration of an identifier for an
13023  // object that has file scope without an initializer, and without a
13024  // storage-class specifier or with the storage-class specifier "static",
13025  // constitutes a tentative definition. Note: A tentative definition with
13026  // external linkage is valid (C99 6.2.2p5).
13027  if (!Var->isInvalidDecl()) {
13028  if (const IncompleteArrayType *ArrayT
13029  = Context.getAsIncompleteArrayType(Type)) {
13030  if (RequireCompleteSizedType(
13031  Var->getLocation(), ArrayT->getElementType(),
13032  diag::err_array_incomplete_or_sizeless_type))
13033  Var->setInvalidDecl();
13034  } else if (Var->getStorageClass() == SC_Static) {
13035  // C99 6.9.2p3: If the declaration of an identifier for an object is
13036  // a tentative definition and has internal linkage (C99 6.2.2p3), the
13037  // declared type shall not be an incomplete type.
13038  // NOTE: code such as the following
13039  // static struct s;
13040  // struct s { int a; };
13041  // is accepted by gcc. Hence here we issue a warning instead of
13042  // an error and we do not invalidate the static declaration.
13043  // NOTE: to avoid multiple warnings, only check the first declaration.
13044  if (Var->isFirstDecl())
13045  RequireCompleteType(Var->getLocation(), Type,
13046  diag::ext_typecheck_decl_incomplete_type);
13047  }
13048  }
13049 
13050  // Record the tentative definition; we're done.
13051  if (!Var->isInvalidDecl())
13052  TentativeDefinitions.push_back(Var);
13053  return;
13054  }
13055 
13056  // Provide a specific diagnostic for uninitialized variable
13057  // definitions with incomplete array type.
13058  if (Type->isIncompleteArrayType()) {
13059  Diag(Var->getLocation(),
13060  diag::err_typecheck_incomplete_array_needs_initializer);
13061  Var->setInvalidDecl();
13062  return;
13063  }
13064 
13065  // Provide a specific diagnostic for uninitialized variable
13066  // definitions with reference type.
13067  if (Type->isReferenceType()) {
13068  Diag(Var->getLocation(), diag::err_reference_var_requires_init)
13069  << Var << SourceRange(Var->getLocation(), Var->getLocation());
13070  Var->setInvalidDecl();
13071  return;
13072  }
13073 
13074  // Do not attempt to type-check the default initializer for a
13075  // variable with dependent type.
13076  if (Type->isDependentType())
13077  return;
13078 
13079  if (Var->isInvalidDecl())
13080  return;
13081 
13082  if (!Var->hasAttr<AliasAttr>()) {
13083  if (RequireCompleteType(Var->getLocation(),
13084  Context.getBaseElementType(Type),
13085  diag::err_typecheck_decl_incomplete_type)) {
13086  Var->setInvalidDecl();
13087  return;
13088  }
13089  } else {
13090  return;
13091  }
13092 
13093  // The variable can not have an abstract class type.
13094  if (RequireNonAbstractType(Var->getLocation(), Type,
13095  diag::err_abstract_type_in_decl,
13096  AbstractVariableType)) {
13097  Var->setInvalidDecl();
13098  return;
13099  }
13100 
13101  // Check for jumps past the implicit initializer. C++0x
13102  // clarifies that this applies to a "variable with automatic
13103  // storage duration", not a "local variable".
13104  // C++11 [stmt.dcl]p3
13105  // A program that jumps from a point where a variable with automatic
13106  // storage duration is not in scope to a point where it is in scope is
13107  // ill-formed unless the variable has scalar type, class type with a
13108  // trivial default constructor and a trivial destructor, a cv-qualified
13109  // version of one of these types, or an array of one of the preceding
13110  // types and is declared without an initializer.
13111  if (getLangOpts().CPlusPlus && Var->hasLocalStorage()) {
13112  if (const RecordType *Record
13113  = Context.getBaseElementType(Type)->getAs<RecordType>()) {
13114  CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record->getDecl());
13115  // Mark the function (if we're in one) for further checking even if the
13116  // looser rules of C++11 do not require such checks, so that we can
13117  // diagnose incompatibilities with C++98.
13118  if (!CXXRecord->isPOD())
13119  setFunctionHasBranchProtectedScope();
13120  }
13121  }
13122  // In OpenCL, we can't initialize objects in the __local address space,
13123  // even implicitly, so don't synthesize an implicit initializer.
13124  if (getLangOpts().OpenCL &&
13125  Var->getType().getAddressSpace() == LangAS::opencl_local)
13126  return;
13127  // In SYCL explicit SIMD extension "private global" variables can't be
13128  // initialized even implicitly, so don't synthesize an implicit initializer.
13129  if (isSYCLEsimdPrivateGlobal(Var))
13130  return;
13131 
13132  // C++03 [dcl.init]p9:
13133  // If no initializer is specified for an object, and the
13134  // object is of (possibly cv-qualified) non-POD class type (or
13135  // array thereof), the object shall be default-initialized; if
13136  // the object is of const-qualified type, the underlying class
13137  // type shall have a user-declared default
13138  // constructor. Otherwise, if no initializer is specified for
13139  // a non- static object, the object and its subobjects, if
13140  // any, have an indeterminate initial value); if the object
13141  // or any of its subobjects are of const-qualified type, the
13142  // program is ill-formed.
13143  // C++0x [dcl.init]p11:
13144  // If no initializer is specified for an object, the object is
13145  // default-initialized; [...].
13148  = InitializationKind::CreateDefault(Var->getLocation());
13149 
13150  InitializationSequence InitSeq(*this, Entity, Kind, None);
13151  ExprResult Init = InitSeq.Perform(*this, Entity, Kind, None);
13152 
13153  if (Init.get()) {
13154  Var->setInit(MaybeCreateExprWithCleanups(Init.get()));
13155  // This is important for template substitution.
13156  Var->setInitStyle(VarDecl::CallInit);
13157  } else if (Init.isInvalid()) {
13158  // If default-init fails, attach a recovery-expr initializer to track
13159  // that initialization was attempted and failed.
13160  auto RecoveryExpr =
13161  CreateRecoveryExpr(Var->getLocation(), Var->getLocation(), {});
13162  if (RecoveryExpr.get())
13163  Var->setInit(RecoveryExpr.get());
13164  }
13165 
13166  CheckCompleteVariableDeclaration(Var);
13167  }
13168 }
13169 
13171  // If there is no declaration, there was an error parsing it. Ignore it.
13172  if (!D)
13173  return;
13174 
13175  VarDecl *VD = dyn_cast<VarDecl>(D);
13176  if (!VD) {
13177  Diag(D->getLocation(), diag::err_for_range_decl_must_be_var);
13178  D->setInvalidDecl();
13179  return;
13180  }
13181 
13182  VD->setCXXForRangeDecl(true);
13183 
13184  // for-range-declaration cannot be given a storage class specifier.
13185  int Error = -1;
13186  switch (VD->getStorageClass()) {
13187  case SC_None:
13188  break;
13189  case SC_Extern:
13190  Error = 0;
13191  break;
13192  case SC_Static:
13193  Error = 1;
13194  break;
13195  case SC_PrivateExtern:
13196  Error = 2;
13197  break;
13198  case SC_Auto:
13199  Error = 3;
13200  break;
13201  case SC_Register:
13202  Error = 4;
13203  break;
13204  }
13205 
13206  // for-range-declaration cannot be given a storage class specifier con't.
13207  switch (VD->getTSCSpec()) {
13208  case TSCS_thread_local:
13209  Error = 6;
13210  break;
13211  case TSCS___thread:
13212  case TSCS__Thread_local:
13213  case TSCS_unspecified:
13214  break;
13215  }
13216 
13217  if (Error != -1) {
13218  Diag(VD->getOuterLocStart(), diag::err_for_range_storage_class)
13219  << VD << Error;
13220  D->setInvalidDecl();
13221  }
13222 }
13223 
13225  IdentifierInfo *Ident,
13226  ParsedAttributes &Attrs) {
13227  // C++1y [stmt.iter]p1:
13228  // A range-based for statement of the form
13229  // for ( for-range-identifier : for-range-initializer ) statement
13230  // is equivalent to
13231  // for ( auto&& for-range-identifier : for-range-initializer ) statement
13232  DeclSpec DS(Attrs.getPool().getFactory());
13233 
13234  const char *PrevSpec;
13235  unsigned DiagID;
13236  DS.SetTypeSpecType(DeclSpec::TST_auto, IdentLoc, PrevSpec, DiagID,
13237  getPrintingPolicy());
13238 
13240  D.SetIdentifier(Ident, IdentLoc);
13241  D.takeAttributes(Attrs);
13242 
13243  D.AddTypeInfo(DeclaratorChunk::getReference(0, IdentLoc, /*lvalue*/ false),
13244  IdentLoc);
13245  Decl *Var = ActOnDeclarator(S, D);
13246  cast<VarDecl>(Var)->setCXXForRangeDecl(true);
13247  FinalizeDeclaration(Var);
13248  return ActOnDeclStmt(FinalizeDeclaratorGroup(S, DS, Var), IdentLoc,
13249  Attrs.Range.getEnd().isValid() ? Attrs.Range.getEnd()
13250  : IdentLoc);
13251 }
13252 
13254  if (var->isInvalidDecl()) return;
13255 
13256  MaybeAddCUDAConstantAttr(var);
13257 
13258  if (getLangOpts().OpenCL) {
13259  // OpenCL v2.0 s6.12.5 - Every block variable declaration must have an
13260  // initialiser
13261  if (var->getTypeSourceInfo()->getType()->isBlockPointerType() &&
13262  !var->hasInit()) {
13263  Diag(var->getLocation(), diag::err_opencl_invalid_block_declaration)
13264  << 1 /*Init*/;
13265  var->setInvalidDecl();
13266  return;
13267  }
13268  }
13269 
13270  if (getLangOpts().SYCLIsDevice)
13271  checkSYCLDeviceVarDecl(var);
13272 
13273  // In Objective-C, don't allow jumps past the implicit initialization of a
13274  // local retaining variable.
13275  if (getLangOpts().ObjC &&
13276  var->hasLocalStorage()) {
13277  switch (var->getType().getObjCLifetime()) {
13278  case Qualifiers::OCL_None:
13281  break;
13282 
13283  case Qualifiers::OCL_Weak:
13285  setFunctionHasBranchProtectedScope();
13286  break;
13287  }
13288  }
13289 
13290  if (var->hasLocalStorage() &&
13291  var->getType().isDestructedType() == QualType::DK_nontrivial_c_struct)
13292  setFunctionHasBranchProtectedScope();
13293 
13294  // Warn about externally-visible variables being defined without a
13295  // prior declaration. We only want to do this for global
13296  // declarations, but we also specifically need to avoid doing it for
13297  // class members because the linkage of an anonymous class can
13298  // change if it's later given a typedef name.
13299  if (var->isThisDeclarationADefinition() &&
13300  var->getDeclContext()->getRedeclContext()->isFileContext() &&
13301  var->isExternallyVisible() && var->hasLinkage() &&
13302  !var->isInline() && !var->getDescribedVarTemplate() &&
13303  !isa<VarTemplatePartialSpecializationDecl>(var) &&
13304  !isTemplateInstantiation(var->getTemplateSpecializationKind()) &&
13305  !getDiagnostics().isIgnored(diag::warn_missing_variable_declarations,
13306  var->getLocation())) {
13307  // Find a previous declaration that's not a definition.
13308  VarDecl *prev = var->getPreviousDecl();
13309  while (prev && prev->isThisDeclarationADefinition())
13310  prev = prev->getPreviousDecl();
13311 
13312  if (!prev) {
13313  Diag(var->getLocation(), diag::warn_missing_variable_declarations) << var;
13314  Diag(var->getTypeSpecStartLoc(), diag::note_static_for_internal_linkage)
13315  << /* variable */ 0;
13316  }
13317  }
13318 
13319  // Cache the result of checking for constant initialization.
13320  Optional<bool> CacheHasConstInit;
13321  const Expr *CacheCulprit = nullptr;
13322  auto checkConstInit = [&]() mutable {
13323  if (!CacheHasConstInit)
13324  CacheHasConstInit = var->getInit()->isConstantInitializer(
13325  Context, var->getType()->isReferenceType(), &CacheCulprit);
13326  return *CacheHasConstInit;
13327  };
13328 
13329  if (var->getTLSKind() == VarDecl::TLS_Static) {
13330  if (var->getType().isDestructedType()) {
13331  // GNU C++98 edits for __thread, [basic.start.term]p3:
13332  // The type of an object with thread storage duration shall not
13333  // have a non-trivial destructor.
13334  Diag(var->getLocation(), diag::err_thread_nontrivial_dtor);
13335  if (getLangOpts().CPlusPlus11)
13336  Diag(var->getLocation(), diag::note_use_thread_local);
13337  } else if (getLangOpts().CPlusPlus && var->hasInit()) {
13338  if (!checkConstInit()) {
13339  // GNU C++98 edits for __thread, [basic.start.init]p4:
13340  // An object of thread storage duration shall not require dynamic
13341  // initialization.
13342  // FIXME: Need strict checking here.
13343  Diag(CacheCulprit->getExprLoc(), diag::err_thread_dynamic_init)
13344  << CacheCulprit->getSourceRange();
13345  if (getLangOpts().CPlusPlus11)
13346  Diag(var->getLocation(), diag::note_use_thread_local);
13347  }
13348  }
13349  }
13350 
13351 
13352  if (!var->getType()->isStructureType() && var->hasInit() &&
13353  isa<InitListExpr>(var->getInit())) {
13354  const auto *ILE = cast<InitListExpr>(var->getInit());
13355  unsigned NumInits = ILE->getNumInits();
13356  if (NumInits > 2)
13357  for (unsigned I = 0; I < NumInits; ++I) {
13358  const auto *Init = ILE->getInit(I);
13359  if (!Init)
13360  break;
13361  const auto *SL = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13362  if (!SL)
13363  break;
13364 
13365  unsigned NumConcat = SL->getNumConcatenated();
13366  // Diagnose missing comma in string array initialization.
13367  // Do not warn when all the elements in the initializer are concatenated
13368  // together. Do not warn for macros too.
13369  if (NumConcat == 2 && !SL->getBeginLoc().isMacroID()) {
13370  bool OnlyOneMissingComma = true;
13371  for (unsigned J = I + 1; J < NumInits; ++J) {
13372  const auto *Init = ILE->getInit(J);
13373  if (!Init)
13374  break;
13375  const auto *SLJ = dyn_cast<StringLiteral>(Init->IgnoreImpCasts());
13376  if (!SLJ || SLJ->getNumConcatenated() > 1) {
13377  OnlyOneMissingComma = false;
13378  break;
13379  }
13380  }
13381 
13382  if (OnlyOneMissingComma) {
13384  for (unsigned i = 0; i < NumConcat - 1; ++i)
13385  Hints.push_back(FixItHint::CreateInsertion(
13386  PP.getLocForEndOfToken(SL->getStrTokenLoc(i)), ","));
13387 
13388  Diag(SL->getStrTokenLoc(1),
13389  diag::warn_concatenated_literal_array_init)
13390  << Hints;
13391  Diag(SL->getBeginLoc(),
13392  diag::note_concatenated_string_literal_silence);
13393  }
13394  // In any case, stop now.
13395  break;
13396  }
13397  }
13398  }
13399 
13400 
13401  QualType type = var->getType();
13402 
13403  if (var->hasAttr<BlocksAttr>())
13404  getCurFunction()->addByrefBlockVar(var);
13405 
13406  Expr *Init = var->getInit();
13407  bool GlobalStorage = var->hasGlobalStorage();
13408  bool IsGlobal = GlobalStorage && !var->isStaticLocal();
13409  QualType baseType = Context.getBaseElementType(type);
13410  bool HasConstInit = true;
13411 
13412  // Check whether the initializer is sufficiently constant.
13413  if (getLangOpts().CPlusPlus && !type->isDependentType() && Init &&
13414  !Init->isValueDependent() &&
13415  (GlobalStorage || var->isConstexpr() ||
13416  var->mightBeUsableInConstantExpressions(Context))) {
13417  // If this variable might have a constant initializer or might be usable in
13418  // constant expressions, check whether or not it actually is now. We can't
13419  // do this lazily, because the result might depend on things that change
13420  // later, such as which constexpr functions happen to be defined.
13422  if (!getLangOpts().CPlusPlus11) {
13423  // Prior to C++11, in contexts where a constant initializer is required,
13424  // the set of valid constant initializers is described by syntactic rules
13425  // in [expr.const]p2-6.
13426  // FIXME: Stricter checking for these rules would be useful for constinit /
13427  // -Wglobal-constructors.
13428  HasConstInit = checkConstInit();
13429 
13430  // Compute and cache the constant value, and remember that we have a
13431  // constant initializer.
13432  if (HasConstInit) {
13433  (void)var->checkForConstantInitialization(Notes);
13434  Notes.clear();
13435  } else if (CacheCulprit) {
13436  Notes.emplace_back(CacheCulprit->getExprLoc(),
13437  PDiag(diag::note_invalid_subexpr_in_const_expr));
13438  Notes.back().second << CacheCulprit->getSourceRange();
13439  }
13440  } else {
13441  // Evaluate the initializer to see if it's a constant initializer.
13442  HasConstInit = var->checkForConstantInitialization(Notes);
13443  }
13444 
13445  if (HasConstInit) {
13446  // FIXME: Consider replacing the initializer with a ConstantExpr.
13447  } else if (var->isConstexpr()) {
13448  SourceLocation DiagLoc = var->getLocation();
13449  // If the note doesn't add any useful information other than a source
13450  // location, fold it into the primary diagnostic.
13451  if (Notes.size() == 1 && Notes[0].second.getDiagID() ==
13452  diag::note_invalid_subexpr_in_const_expr) {
13453  DiagLoc = Notes[0].first;
13454  Notes.clear();
13455  }
13456  Diag(DiagLoc, diag::err_constexpr_var_requires_const_init)
13457  << var << Init->getSourceRange();
13458  for (unsigned I = 0, N = Notes.size(); I != N; ++I)
13459  Diag(Notes[I].first, Notes[I].second);
13460  } else if (GlobalStorage && var->hasAttr<ConstInitAttr>()) {
13461  auto *Attr = var->getAttr<ConstInitAttr>();
13462  Diag(var->getLocation(), diag::err_require_constant_init_failed)
13463  << Init->getSourceRange();
13464  Diag(Attr->getLocation(), diag::note_declared_required_constant_init_here)
13465  << Attr->getRange() << Attr->isConstinit();
13466  for (auto &it : Notes)
13467  Diag(it.first, it.second);
13468  } else if (IsGlobal &&
13469  !getDiagnostics().isIgnored(diag::warn_global_constructor,
13470  var->getLocation())) {
13471  // Warn about globals which don't have a constant initializer. Don't
13472  // warn about globals with a non-trivial destructor because we already
13473  // warned about them.
13474  CXXRecordDecl *RD = baseType->getAsCXXRecordDecl();
13475  if (!(RD && !RD->hasTrivialDestructor())) {
13476  // checkConstInit() here permits trivial default initialization even in
13477  // C++11 onwards, where such an initializer is not a constant initializer
13478  // but nonetheless doesn't require a global constructor.
13479  if (!checkConstInit())
13480  Diag(var->getLocation(), diag::warn_global_constructor)
13481  << Init->getSourceRange();
13482  }
13483  }
13484  }
13485 
13486  // Apply section attributes and pragmas to global variables.
13487  if (GlobalStorage && var->isThisDeclarationADefinition() &&
13488  !inTemplateInstantiation()) {
13489  PragmaStack<StringLiteral *> *Stack = nullptr;
13490  int SectionFlags = ASTContext::PSF_Read;
13491  if (var->getType().isConstQualified()) {
13492  if (HasConstInit)
13493  Stack = &ConstSegStack;
13494  else {
13495  Stack = &BSSSegStack;
13496  SectionFlags |= ASTContext::PSF_Write;
13497  }
13498  } else if (var->hasInit() && HasConstInit) {
13499  Stack = &DataSegStack;
13500  SectionFlags |= ASTContext::PSF_Write;
13501  } else {
13502  Stack = &BSSSegStack;
13503  SectionFlags |= ASTContext::PSF_Write;
13504  }
13505  if (const SectionAttr *SA = var->getAttr<SectionAttr>()) {
13506  if (SA->getSyntax() == AttributeCommonInfo::AS_Declspec)
13507  SectionFlags |= ASTContext::PSF_Implicit;
13508  UnifySection(SA->getName(), SectionFlags, var);
13509  } else if (Stack->CurrentValue) {
13510  SectionFlags |= ASTContext::PSF_Implicit;
13511  auto SectionName = Stack->CurrentValue->getString();
13512  var->addAttr(SectionAttr::CreateImplicit(
13513  Context, SectionName, Stack->CurrentPragmaLocation,
13514  AttributeCommonInfo::AS_Pragma, SectionAttr::Declspec_allocate));
13515  if (UnifySection(SectionName, SectionFlags, var))
13516  var->dropAttr<SectionAttr>();
13517  }
13518 
13519  // Apply the init_seg attribute if this has an initializer. If the
13520  // initializer turns out to not be dynamic, we'll end up ignoring this
13521  // attribute.
13522  if (CurInitSeg && var->getInit())
13523  var->addAttr(InitSegAttr::CreateImplicit(Context, CurInitSeg->getString(),
13524  CurInitSegLoc,
13526  }
13527 
13528  // All the following checks are C++ only.
13529  if (!getLangOpts().CPlusPlus) {
13530  // If this variable must be emitted, add it as an initializer for the
13531  // current module.
13532  if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13533  Context.addModuleInitializer(ModuleScopes.back().Module, var);
13534  return;
13535  }
13536 
13537  // Require the destructor.
13538  if (!type->isDependentType())
13539  if (const RecordType *recordType = baseType->getAs<RecordType>())
13540  FinalizeVarWithDestructor(var, recordType);
13541 
13542  // If this variable must be emitted, add it as an initializer for the current
13543  // module.
13544  if (Context.DeclMustBeEmitted(var) && !ModuleScopes.empty())
13545  Context.addModuleInitializer(ModuleScopes.back().Module, var);
13546 
13547  // Build the bindings if this is a structured binding declaration.
13548  if (auto *DD = dyn_cast<DecompositionDecl>(var))
13549  CheckCompleteDecompositionDeclaration(DD);
13550 }
13551 
13552 /// Check if VD needs to be dllexport/dllimport due to being in a
13553 /// dllexport/import function.
13555  assert(VD->isStaticLocal());
13556 
13557  auto *FD = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13558 
13559  // Find outermost function when VD is in lambda function.
13560  while (FD && !getDLLAttr(FD) &&
13561  !FD->hasAttr<DLLExportStaticLocalAttr>() &&
13562  !FD->hasAttr<DLLImportStaticLocalAttr>()) {
13563  FD = dyn_cast_or_null<FunctionDecl>(FD->getParentFunctionOrMethod());
13564  }
13565 
13566  if (!FD)
13567  return;
13568 
13569  // Static locals inherit dll attributes from their function.
13570  if (Attr *A = getDLLAttr(FD)) {
13571  auto *NewAttr = cast<InheritableAttr>(A->clone(getASTContext()));
13572  NewAttr->setInherited(true);
13573  VD->addAttr(NewAttr);
13574  } else if (Attr *A = FD->getAttr<DLLExportStaticLocalAttr>()) {
13575  auto *NewAttr = DLLExportAttr::CreateImplicit(getASTContext(), *A);
13576  NewAttr->setInherited(true);
13577  VD->addAttr(NewAttr);
13578 
13579  // Export this function to enforce exporting this static variable even
13580  // if it is not used in this compilation unit.
13581  if (!FD->hasAttr<DLLExportAttr>())
13582  FD->addAttr(NewAttr);
13583 
13584  } else if (Attr *A = FD->getAttr<DLLImportStaticLocalAttr>()) {
13585  auto *NewAttr = DLLImportAttr::CreateImplicit(getASTContext(), *A);
13586  NewAttr->setInherited(true);
13587  VD->addAttr(NewAttr);
13588  }
13589 }
13590 
13591 /// FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform
13592 /// any semantic actions necessary after any initializer has been attached.
13594  // Note that we are no longer parsing the initializer for this declaration.
13595  ParsingInitForAutoVars.erase(ThisDecl);
13596 
13597  VarDecl *VD = dyn_cast_or_null<VarDecl>(ThisDecl);
13598  if (!VD)
13599  return;
13600 
13601  // Apply an implicit SectionAttr if '#pragma clang section bss|data|rodata' is active
13602  if (VD->hasGlobalStorage() && VD->isThisDeclarationADefinition() &&
13603  !inTemplateInstantiation() && !VD->hasAttr<SectionAttr>()) {
13604  if (PragmaClangBSSSection.Valid)
13605  VD->addAttr(PragmaClangBSSSectionAttr::CreateImplicit(
13606  Context, PragmaClangBSSSection.SectionName,
13607  PragmaClangBSSSection.PragmaLocation,
13609  if (PragmaClangDataSection.Valid)
13610  VD->addAttr(PragmaClangDataSectionAttr::CreateImplicit(
13611  Context, PragmaClangDataSection.SectionName,
13612  PragmaClangDataSection.PragmaLocation,
13614  if (PragmaClangRodataSection.Valid)
13615  VD->addAttr(PragmaClangRodataSectionAttr::CreateImplicit(
13616  Context, PragmaClangRodataSection.SectionName,
13617  PragmaClangRodataSection.PragmaLocation,
13619  if (PragmaClangRelroSection.Valid)
13620  VD->addAttr(PragmaClangRelroSectionAttr::CreateImplicit(
13621  Context, PragmaClangRelroSection.SectionName,
13622  PragmaClangRelroSection.PragmaLocation,
13624  }
13625 
13626  if (auto *DD = dyn_cast<DecompositionDecl>(ThisDecl)) {
13627  for (auto *BD : DD->bindings()) {
13628  FinalizeDeclaration(BD);
13629  }
13630  }
13631 
13632  checkAttributesAfterMerging(*this, *VD);
13633 
13634  // Perform TLS alignment check here after attributes attached to the variable
13635  // which may affect the alignment have been processed. Only perform the check
13636  // if the target has a maximum TLS alignment (zero means no constraints).
13637  if (unsigned MaxAlign = Context.getTargetInfo().getMaxTLSAlign()) {
13638  // Protect the check so that it's not performed on dependent types and
13639  // dependent alignments (we can't determine the alignment in that case).
13640  if (VD->getTLSKind() && !VD->hasDependentAlignment()) {
13641  CharUnits MaxAlignChars = Context.toCharUnitsFromBits(MaxAlign);
13642  if (Context.getDeclAlign(VD) > MaxAlignChars) {
13643  Diag(VD->getLocation(), diag::err_tls_var_aligned_over_maximum)
13644  << (unsigned)Context.getDeclAlign(VD).getQuantity() << VD
13645  << (unsigned)MaxAlignChars.getQuantity();
13646  }
13647  }
13648  }
13649 
13650  if (VD->isStaticLocal())
13651  CheckStaticLocalForDllExport(VD);
13652 
13653  // Perform check for initializers of device-side global variables.
13654  // CUDA allows empty constructors as initializers (see E.2.3.1, CUDA
13655  // 7.5). We must also apply the same checks to all __shared__
13656  // variables whether they are local or not. CUDA also allows
13657  // constant initializers for __constant__ and __device__ variables.
13658  if (getLangOpts().CUDA)
13659  checkAllowedCUDAInitializer(VD);
13660 
13661  // Grab the dllimport or dllexport attribute off of the VarDecl.
13662  const InheritableAttr *DLLAttr = getDLLAttr(VD);
13663 
13664  // Imported static data members cannot be defined out-of-line.
13665  if (const auto *IA = dyn_cast_or_null<DLLImportAttr>(DLLAttr)) {
13666  if (VD->isStaticDataMember() && VD->isOutOfLine() &&
13668  // We allow definitions of dllimport class template static data members
13669  // with a warning.
13670  CXXRecordDecl *Context =
13671  cast<CXXRecordDecl>(VD->getFirstDecl()->getDeclContext());
13672  bool IsClassTemplateMember =
13673  isa<ClassTemplatePartialSpecializationDecl>(Context) ||
13674  Context->getDescribedClassTemplate();
13675 
13676  Diag(VD->getLocation(),
13677  IsClassTemplateMember
13678  ? diag::warn_attribute_dllimport_static_field_definition
13679  : diag::err_attribute_dllimport_static_field_definition);
13680  Diag(IA->getLocation(), diag::note_attribute);
13681  if (!IsClassTemplateMember)
13682  VD->setInvalidDecl();
13683  }
13684  }
13685 
13686  // dllimport/dllexport variables cannot be thread local, their TLS index
13687  // isn't exported with the variable.
13688  if (DLLAttr && VD->getTLSKind()) {
13689  auto *F = dyn_cast_or_null<FunctionDecl>(VD->getParentFunctionOrMethod());
13690  if (F && getDLLAttr(F)) {
13691  assert(VD->isStaticLocal());
13692  // But if this is a static local in a dlimport/dllexport function, the
13693  // function will never be inlined, which means the var would never be
13694  // imported, so having it marked import/export is safe.
13695  } else {
13696  Diag(VD->getLocation(), diag::err_attribute_dll_thread_local) << VD
13697  << DLLAttr;
13698  VD->setInvalidDecl();
13699  }
13700  }
13701 
13702  if (UsedAttr *Attr = VD->getAttr<UsedAttr>()) {
13703  if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13704  Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13705  << Attr;
13706  VD->dropAttr<UsedAttr>();
13707  }
13708  }
13709  if (RetainAttr *Attr = VD->getAttr<RetainAttr>()) {
13710  if (!Attr->isInherited() && !VD->isThisDeclarationADefinition()) {
13711  Diag(Attr->getLocation(), diag::warn_attribute_ignored_on_non_definition)
13712  << Attr;
13713  VD->dropAttr<RetainAttr>();
13714  }
13715  }
13716 
13717  const DeclContext *DC = VD->getDeclContext();
13718  // If there's a #pragma GCC visibility in scope, and this isn't a class
13719  // member, set the visibility of this variable.
13720  if (DC->getRedeclContext()->isFileContext() && VD->isExternallyVisible())
13721  AddPushedVisibilityAttribute(VD);
13722 
13723  // FIXME: Warn on unused var template partial specializations.
13724  if (VD->isFileVarDecl() && !isa<VarTemplatePartialSpecializationDecl>(VD))
13725  MarkUnusedFileScopedDecl(VD);
13726 
13727  // Now we have parsed the initializer and can update the table of magic
13728  // tag values.
13729  if (!VD->hasAttr<TypeTagForDatatypeAttr>() ||
13731  return;
13732 
13733  for (const auto *I : ThisDecl->specific_attrs<TypeTagForDatatypeAttr>()) {
13734  const Expr *MagicValueExpr = VD->getInit();
13735  if (!MagicValueExpr) {
13736  continue;
13737  }
13738  Optional<llvm::APSInt> MagicValueInt;
13739  if (!(MagicValueInt = MagicValueExpr->getIntegerConstantExpr(Context))) {
13740  Diag(I->getRange().getBegin(),
13741  diag::err_type_tag_for_datatype_not_ice)
13742  << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13743  continue;
13744  }
13745  if (MagicValueInt->getActiveBits() > 64) {
13746  Diag(I->getRange().getBegin(),
13747  diag::err_type_tag_for_datatype_too_large)
13748  << LangOpts.CPlusPlus << MagicValueExpr->getSourceRange();
13749  continue;
13750  }
13751  uint64_t MagicValue = MagicValueInt->getZExtValue();
13752  RegisterTypeTagForDatatype(I->getArgumentKind(),
13753  MagicValue,
13754  I->getMatchingCType(),
13755  I->getLayoutCompatible(),
13756  I->getMustBeNull());
13757  }
13758 }
13759 
13760 static bool hasDeducedAuto(DeclaratorDecl *DD) {
13761  auto *VD = dyn_cast<VarDecl>(DD);
13762  return VD && !VD->getType()->hasAutoForTrailingReturnType();
13763 }
13764 
13767  SmallVector<Decl*, 8> Decls;
13768 
13769  if (DS.isTypeSpecOwned())
13770  Decls.push_back(DS.getRepAsDecl());
13771 
13772  DeclaratorDecl *FirstDeclaratorInGroup = nullptr;
13773  DecompositionDecl *FirstDecompDeclaratorInGroup = nullptr;
13774  bool DiagnosedMultipleDecomps = false;
13775  DeclaratorDecl *FirstNonDeducedAutoInGroup = nullptr;
13776  bool DiagnosedNonDeducedAuto = false;
13777 
13778  for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13779  if (Decl *D = Group[i]) {
13780  // For declarators, there are some additional syntactic-ish checks we need
13781  // to perform.
13782  if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
13783  if (!FirstDeclaratorInGroup)
13784  FirstDeclaratorInGroup = DD;
13785  if (!FirstDecompDeclaratorInGroup)
13786  FirstDecompDeclaratorInGroup = dyn_cast<DecompositionDecl>(D);
13787  if (!FirstNonDeducedAutoInGroup && DS.hasAutoTypeSpec() &&
13788  !hasDeducedAuto(DD))
13789  FirstNonDeducedAutoInGroup = DD;
13790 
13791  if (FirstDeclaratorInGroup != DD) {
13792  // A decomposition declaration cannot be combined with any other
13793  // declaration in the same group.
13794  if (FirstDecompDeclaratorInGroup && !DiagnosedMultipleDecomps) {
13795  Diag(FirstDecompDeclaratorInGroup->getLocation(),
13796  diag::err_decomp_decl_not_alone)
13797  << FirstDeclaratorInGroup->getSourceRange()
13798  << DD->getSourceRange();
13799  DiagnosedMultipleDecomps = true;
13800  }
13801 
13802  // A declarator that uses 'auto' in any way other than to declare a
13803  // variable with a deduced type cannot be combined with any other
13804  // declarator in the same group.
13805  if (FirstNonDeducedAutoInGroup && !DiagnosedNonDeducedAuto) {
13806  Diag(FirstNonDeducedAutoInGroup->getLocation(),
13807  diag::err_auto_non_deduced_not_alone)
13808  << FirstNonDeducedAutoInGroup->getType()
13810  << FirstDeclaratorInGroup->getSourceRange()
13811  << DD->getSourceRange();
13812  DiagnosedNonDeducedAuto = true;
13813  }
13814  }
13815  }
13816 
13817  Decls.push_back(D);
13818  }
13819  }
13820 
13822  if (TagDecl *Tag = dyn_cast_or_null<TagDecl>(DS.getRepAsDecl())) {
13823  handleTagNumbering(Tag, S);
13824  if (FirstDeclaratorInGroup && !Tag->hasNameForLinkage() &&
13825  getLangOpts().CPlusPlus)
13826  Context.addDeclaratorForUnnamedTagDecl(Tag, FirstDeclaratorInGroup);
13827  }
13828  }
13829 
13830  return BuildDeclaratorGroup(Decls);
13831 }
13832 
13833 /// BuildDeclaratorGroup - convert a list of declarations into a declaration
13834 /// group, performing any necessary semantic checking.
13837  // C++14 [dcl.spec.auto]p7: (DR1347)
13838  // If the type that replaces the placeholder type is not the same in each
13839  // deduction, the program is ill-formed.
13840  if (Group.size() > 1) {
13841  QualType Deduced;
13842  VarDecl *DeducedDecl = nullptr;
13843  for (unsigned i = 0, e = Group.size(); i != e; ++i) {
13844  VarDecl *D = dyn_cast<VarDecl>(Group[i]);
13845  if (!D || D->isInvalidDecl())
13846  break;
13848  if (!DT || DT->getDeducedType().isNull())
13849  continue;
13850  if (Deduced.isNull()) {
13851  Deduced = DT->getDeducedType();
13852  DeducedDecl = D;
13853  } else if (!Context.hasSameType(DT->getDeducedType(), Deduced)) {
13854  auto *AT = dyn_cast<AutoType>(DT);
13855  auto Dia = Diag(D->getTypeSourceInfo()->getTypeLoc().getBeginLoc(),
13856  diag::err_auto_different_deductions)
13857  << (AT ? (unsigned)AT->getKeyword() : 3) << Deduced
13858  << DeducedDecl->getDeclName() << DT->getDeducedType()
13859  << D->getDeclName();
13860  if (DeducedDecl->hasInit())
13861  Dia << DeducedDecl->getInit()->getSourceRange();
13862  if (D->getInit())
13863  Dia << D->getInit()->getSourceRange();
13864  D->setInvalidDecl();
13865  break;
13866  }
13867  }
13868  }
13869 
13870  ActOnDocumentableDecls(Group);
13871 
13872  return DeclGroupPtrTy::make(
13873  DeclGroupRef::Create(Context, Group.data(), Group.size()));
13874 }
13875 
13877  ActOnDocumentableDecls(D);
13878 }
13879 
13881  // Don't parse the comment if Doxygen diagnostics are ignored.
13882  if (Group.empty() || !Group[0])
13883  return;
13884 
13885  if (Diags.isIgnored(diag::warn_doc_param_not_found,
13886  Group[0]->getLocation()) &&
13887  Diags.isIgnored(diag::warn_unknown_comment_command_name,
13888  Group[0]->getLocation()))
13889  return;
13890 
13891  if (Group.size() >= 2) {
13892  // This is a decl group. Normally it will contain only declarations
13893  // produced from declarator list. But in case we have any definitions or
13894  // additional declaration references:
13895  // 'typedef struct S {} S;'
13896  // 'typedef struct S *S;'
13897  // 'struct S *pS;'
13898  // FinalizeDeclaratorGroup adds these as separate declarations.
13899  Decl *MaybeTagDecl = Group[0];
13900  if (MaybeTagDecl && isa<TagDecl>(MaybeTagDecl)) {
13901  Group = Group.slice(1);
13902  }
13903  }
13904 
13905  // FIMXE: We assume every Decl in the group is in the same file.
13906  // This is false when preprocessor constructs the group from decls in
13907  // different files (e. g. macros or #include).
13908  Context.attachCommentsToJustParsedDecls(Group, &getPreprocessor());
13909 }
13910 
13911 /// Common checks for a parameter-declaration that should apply to both function
13912 /// parameters and non-type template parameters.
13914  // Check that there are no default arguments inside the type of this
13915  // parameter.
13916  if (getLangOpts().CPlusPlus)
13917  CheckExtraCXXDefaultArguments(D);
13918 
13919  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
13920  if (D.getCXXScopeSpec().isSet()) {
13921  Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
13922  << D.getCXXScopeSpec().getRange();
13923  }
13924 
13925  // [dcl.meaning]p1: An unqualified-id occurring in a declarator-id shall be a
13926  // simple identifier except [...irrelevant cases...].
13927  switch (D.getName().getKind()) {
13929  break;
13930 
13938  Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name)
13939  << GetNameForDeclarator(D).getName();
13940  break;
13941 
13944  // GetNameForDeclarator would not produce a useful name in this case.
13945  Diag(D.getIdentifierLoc(), diag::err_bad_parameter_name_template_id);
13946  break;
13947  }
13948 }
13949 
13950 /// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
13951 /// to introduce parameters into function prototype scope.
13953  const DeclSpec &DS = D.getDeclSpec();
13954 
13955  // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
13956 
13957  // C++03 [dcl.stc]p2 also permits 'auto'.
13958  StorageClass SC = SC_None;
13960  SC = SC_Register;
13961  // In C++11, the 'register' storage class specifier is deprecated.
13962  // In C++17, it is not allowed, but we tolerate it as an extension.
13963  if (getLangOpts().CPlusPlus11) {
13965  getLangOpts().CPlusPlus17 ? diag::ext_register_storage_class
13966  : diag::warn_deprecated_register)
13968  }
13969  } else if (getLangOpts().CPlusPlus &&
13971  SC = SC_Auto;
13972  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
13974  diag::err_invalid_storage_class_in_func_decl);
13976  }
13977 
13978  if (DeclSpec::TSCS TSCS = DS.getThreadStorageClassSpec())
13979  Diag(DS.getThreadStorageClassSpecLoc(), diag::err_invalid_thread)
13980  << DeclSpec::getSpecifierName(TSCS);
13981  if (DS.isInlineSpecified())
13982  Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
13983  << getLangOpts().CPlusPlus17;
13984  if (DS.hasConstexprSpecifier())
13985  Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr)
13986  << 0 << static_cast<int>(D.getDeclSpec().getConstexprSpecifier());
13987 
13988  DiagnoseFunctionSpecifiers(DS);
13989 
13990  CheckFunctionOrTemplateParamDeclarator(S, D);
13991 
13992  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13993  QualType parmDeclType = TInfo->getType();
13994 
13995  // Check for redeclaration of parameters, e.g. int foo(int x, int x);
13996  IdentifierInfo *II = D.getIdentifier();
13997  if (II) {
13998  LookupResult R(*this, II, D.getIdentifierLoc(), LookupOrdinaryName,
13999  ForVisibleRedeclaration);
14000  LookupName(R, S);
14001  if (R.isSingleResult()) {
14002  NamedDecl *PrevDecl = R.getFoundDecl();
14003  if (PrevDecl->isTemplateParameter()) {
14004  // Maybe we will complain about the shadowed template parameter.
14005  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
14006  // Just pretend that we didn't see the previous declaration.
14007  PrevDecl = nullptr;
14008  } else if (S->isDeclScope(PrevDecl)) {
14009  Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
14010  Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
14011 
14012  // Recover by removing the name
14013  II = nullptr;
14014  D.SetIdentifier(nullptr, D.getIdentifierLoc());
14015  D.setInvalidType(true);
14016  }
14017  }
14018  }
14019 
14020  // Temporarily put parameter variables in the translation unit, not
14021  // the enclosing context. This prevents them from accidentally
14022  // looking like class members in C++.
14023  ParmVarDecl *New =
14024  CheckParameter(Context.getTranslationUnitDecl(), D.getBeginLoc(),
14025  D.getIdentifierLoc(), II, parmDeclType, TInfo, SC);
14026 
14027  if (D.isInvalidType())
14028  New->setInvalidDecl();
14029 
14030  assert(S->isFunctionPrototypeScope());
14031  assert(S->getFunctionPrototypeDepth() >= 1);
14032  New->setScopeInfo(S->getFunctionPrototypeDepth() - 1,
14033  S->getNextFunctionPrototypeIndex());
14034 
14035  // Add the parameter declaration into this scope.
14036  S->AddDecl(New);
14037  if (II)
14038  IdResolver.AddDecl(New);
14039 
14040  ProcessDeclAttributes(S, New, D);
14041 
14043  Diag(New->getLocation(), diag::err_module_private_local)
14044  << 1 << New << SourceRange(D.getDeclSpec().getModulePrivateSpecLoc())
14046 
14047  if (New->hasAttr<BlocksAttr>()) {
14048  Diag(New->getLocation(), diag::err_block_on_nonlocal);
14049  }
14050 
14051  if (getLangOpts().OpenCL)
14052  deduceOpenCLAddressSpace(New);
14053 
14054  return New;
14055 }
14056 
14057 /// Synthesizes a variable for a parameter arising from a
14058 /// typedef.
14060  SourceLocation Loc,
14061  QualType T) {
14062  /* FIXME: setting StartLoc == Loc.
14063  Would it be worth to modify callers so as to provide proper source
14064  location for the unnamed parameters, embedding the parameter's type? */
14065  ParmVarDecl *Param = ParmVarDecl::Create(Context, DC, Loc, Loc, nullptr,
14066  T, Context.getTrivialTypeSourceInfo(T, Loc),
14067  SC_None, nullptr);
14068  Param->setImplicit();
14069  return Param;
14070 }
14071 
14073  // Don't diagnose unused-parameter errors in template instantiations; we
14074  // will already have done so in the template itself.
14075  if (inTemplateInstantiation())
14076  return;
14077 
14078  for (const ParmVarDecl *Parameter : Parameters) {
14079  if (!Parameter->isReferenced() && Parameter->getDeclName() &&
14080  !Parameter->hasAttr<UnusedAttr>()) {
14081  Diag(Parameter->getLocation(), diag::warn_unused_parameter)
14082  << Parameter->getDeclName();
14083  }
14084  }
14085 }
14086 
14088  ArrayRef<ParmVarDecl *> Parameters, QualType ReturnTy, NamedDecl *D) {
14089  if (LangOpts.NumLargeByValueCopy == 0) // No check.
14090  return;
14091 
14092  // Warn if the return value is pass-by-value and larger than the specified
14093  // threshold.
14094  if (!ReturnTy->isDependentType() && ReturnTy.isPODType(Context)) {
14095  unsigned Size = Context.getTypeSizeInChars(ReturnTy).getQuantity();
14096  if (Size > LangOpts.NumLargeByValueCopy)
14097  Diag(D->getLocation(), diag::warn_return_value_size) << D << Size;
14098  }
14099 
14100  // Warn if any parameter is pass-by-value and larger than the specified
14101  // threshold.
14102  for (const ParmVarDecl *Parameter : Parameters) {
14103  QualType T = Parameter->getType();
14104  if (T->isDependentType() || !T.isPODType(Context))
14105  continue;
14106  unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
14107  if (Size > LangOpts.NumLargeByValueCopy)
14108  Diag(Parameter->getLocation(), diag::warn_parameter_size)
14109  << Parameter << Size;
14110  }
14111 }
14112 
14114  SourceLocation NameLoc, IdentifierInfo *Name,
14115  QualType T, TypeSourceInfo *TSInfo,
14116  StorageClass SC) {
14117  // In ARC, infer a lifetime qualifier for appropriate parameter types.
14118  if (getLangOpts().ObjCAutoRefCount &&
14120  T->isObjCLifetimeType()) {
14121 
14122  Qualifiers::ObjCLifetime lifetime;
14123 
14124  // Special cases for arrays:
14125  // - if it's const, use __unsafe_unretained
14126  // - otherwise, it's an error
14127  if (T->isArrayType()) {
14128  if (!T.isConstQualified()) {
14132  NameLoc, diag::err_arc_array_param_no_ownership, T, false));
14133  else
14134  Diag(NameLoc, diag::err_arc_array_param_no_ownership)
14135  << TSInfo->getTypeLoc().getSourceRange();
14136  }
14137  lifetime = Qualifiers::OCL_ExplicitNone;
14138  } else {
14139  lifetime = T->getObjCARCImplicitLifetime();
14140  }
14141  T = Context.getLifetimeQualifiedType(T, lifetime);
14142  }
14143 
14144  ParmVarDecl *New = ParmVarDecl::Create(Context, DC, StartLoc, NameLoc, Name,
14145  Context.getAdjustedParameterType(T),
14146  TSInfo, SC, nullptr);
14147 
14148  // Make a note if we created a new pack in the scope of a lambda, so that
14149  // we know that references to that pack must also be expanded within the
14150  // lambda scope.
14151  if (New->isParameterPack())
14152  if (auto *LSI = getEnclosingLambda())
14153  LSI->LocalPacks.push_back(New);
14154 
14157  checkNonTrivialCUnion(New->getType(), New->getLocation(),
14158  NTCUC_FunctionParam, NTCUK_Destruct|NTCUK_Copy);
14159 
14160  // Parameters can not be abstract class types.
14161  // For record types, this is done by the AbstractClassUsageDiagnoser once
14162  // the class has been completely parsed.
14163  if (!CurContext->isRecord() &&
14164  RequireNonAbstractType(NameLoc, T, diag::err_abstract_type_in_decl,
14165  AbstractParamType))
14166  New->setInvalidDecl();
14167 
14168  // Parameter declarators cannot be interface types. All ObjC objects are
14169  // passed by reference.
14170  if (T->isObjCObjectType()) {
14171  SourceLocation TypeEndLoc =
14172  getLocForEndOfToken(TSInfo->getTypeLoc().getEndLoc());
14173  Diag(NameLoc,
14174  diag::err_object_cannot_be_passed_returned_by_value) << 1 << T
14175  << FixItHint::CreateInsertion(TypeEndLoc, "*");
14176  T = Context.getObjCObjectPointerType(T);
14177  New->setType(T);
14178  }
14179 
14180  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
14181  // duration shall not be qualified by an address-space qualifier."
14182  // Since all parameters have automatic store duration, they can not have
14183  // an address space.
14184  if (T.getAddressSpace() != LangAS::Default &&
14185  // OpenCL allows function arguments declared to be an array of a type
14186  // to be qualified with an address space.
14187  !(getLangOpts().OpenCL &&
14189  Diag(NameLoc, diag::err_arg_with_address_space);
14190  New->setInvalidDecl();
14191  }
14192 
14193  // PPC MMA non-pointer types are not allowed as function argument types.
14194  if (Context.getTargetInfo().getTriple().isPPC64() &&
14195  CheckPPCMMAType(New->getOriginalType(), New->getLocation())) {
14196  New->setInvalidDecl();
14197  }
14198 
14199  return New;
14200 }
14201 
14203  SourceLocation LocAfterDecls) {
14205 
14206  // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
14207  // for a K&R function.
14208  if (!FTI.hasPrototype) {
14209  for (int i = FTI.NumParams; i != 0; /* decrement in loop */) {
14210  --i;
14211  if (FTI.Params[i].Param == nullptr) {
14212  SmallString<256> Code;
14213  llvm::raw_svector_ostream(Code)
14214  << " int " << FTI.Params[i].Ident->getName() << ";\n";
14215  Diag(FTI.Params[i].IdentLoc, diag::ext_param_not_declared)
14216  << FTI.Params[i].Ident
14217  << FixItHint::CreateInsertion(LocAfterDecls, Code);
14218 
14219  // Implicitly declare the argument as type 'int' for lack of a better
14220  // type.
14221  AttributeFactory attrs;
14222  DeclSpec DS(attrs);
14223  const char* PrevSpec; // unused
14224  unsigned DiagID; // unused
14225  DS.SetTypeSpecType(DeclSpec::TST_int, FTI.Params[i].IdentLoc, PrevSpec,
14226  DiagID, Context.getPrintingPolicy());
14227  // Use the identifier location for the type source range.
14228  DS.SetRangeStart(FTI.Params[i].IdentLoc);
14229  DS.SetRangeEnd(FTI.Params[i].IdentLoc);
14231  ParamD.SetIdentifier(FTI.Params[i].Ident, FTI.Params[i].IdentLoc);
14232  FTI.Params[i].Param = ActOnParamDeclarator(S, ParamD);
14233  }
14234  }
14235  }
14236 }
14237 
14238 Decl *
14240  MultiTemplateParamsArg TemplateParameterLists,
14241  SkipBodyInfo *SkipBody) {
14242  assert(getCurFunctionDecl() == nullptr && "Function parsing confused");
14243  assert(D.isFunctionDeclarator() && "Not a function declarator!");
14244  Scope *ParentScope = FnBodyScope->getParent();
14245 
14246  // Check if we are in an `omp begin/end declare variant` scope. If we are, and
14247  // we define a non-templated function definition, we will create a declaration
14248  // instead (=BaseFD), and emit the definition with a mangled name afterwards.
14249  // The base function declaration will have the equivalent of an `omp declare
14250  // variant` annotation which specifies the mangled definition as a
14251  // specialization function under the OpenMP context defined as part of the
14252  // `omp begin declare variant`.
14254  if (LangOpts.OpenMP && isInOpenMPDeclareVariantScope())
14255  ActOnStartOfFunctionDefinitionInOpenMPDeclareVariantScope(
14256  ParentScope, D, TemplateParameterLists, Bases);
14257 
14259  Decl *DP = HandleDeclarator(ParentScope, D, TemplateParameterLists);
14260  Decl *Dcl = ActOnStartOfFunctionDef(FnBodyScope, DP, SkipBody);
14261 
14262  if (!Bases.empty())
14263  ActOnFinishedFunctionDefinitionInOpenMPDeclareVariantScope(Dcl, Bases);
14264 
14265  return Dcl;
14266 }
14267 
14269  Consumer.HandleInlineFunctionDefinition(D);
14270 }
14271 
14272 static bool
14274  const FunctionDecl *&PossiblePrototype) {
14275  // Don't warn about invalid declarations.
14276  if (FD->isInvalidDecl())
14277  return false;
14278 
14279  // Or declarations that aren't global.
14280  if (!FD->isGlobal())
14281  return false;
14282 
14283  // Don't warn about C++ member functions.
14284  if (isa<CXXMethodDecl>(FD))
14285  return false;
14286 
14287  // Don't warn about 'main'.
14288  if (isa<TranslationUnitDecl>(FD->getDeclContext()->getRedeclContext()))
14289  if (IdentifierInfo *II = FD->getIdentifier())
14290  if (II->isStr("main") || II->isStr("efi_main"))
14291  return false;
14292 
14293  // Don't warn about inline functions.
14294  if (FD->isInlined())
14295  return false;
14296 
14297  // Don't warn about function templates.
14298  if (FD->getDescribedFunctionTemplate())
14299  return false;
14300 
14301  // Don't warn about function template specializations.
14303  return false;
14304 
14305  // Don't warn for OpenCL kernels.
14306  if (FD->hasAttr<OpenCLKernelAttr>())
14307  return false;
14308 
14309  // Don't warn on explicitly deleted functions.
14310  if (FD->isDeleted())
14311  return false;
14312 
14313  // Don't warn on implicitly local functions (such as having local-typed
14314  // parameters).
14315  if (!FD->isExternallyVisible())
14316  return false;
14317 
14318  for (const FunctionDecl *Prev = FD->getPreviousDecl();
14319  Prev; Prev = Prev->getPreviousDecl()) {
14320  // Ignore any declarations that occur in function or method
14321  // scope, because they aren't visible from the header.
14322  if (Prev->getLexicalDeclContext()->isFunctionOrMethod())
14323  continue;
14324 
14325  PossiblePrototype = Prev;
14326  return Prev->getType()->isFunctionNoProtoType();
14327  }
14328 
14329  return true;
14330 }
14331 
14332 void
14334  const FunctionDecl *EffectiveDefinition,
14335  SkipBodyInfo *SkipBody) {
14336  const FunctionDecl *Definition = EffectiveDefinition;
14337  if (!Definition &&
14338  !FD->isDefined(Definition, /*CheckForPendingFriendDefinition*/ true))
14339  return;
14340 
14341  if (Definition->getFriendObjectKind() != Decl::FOK_None) {
14342  if (FunctionDecl *OrigDef = Definition->getInstantiatedFromMemberFunction()) {
14343  if (FunctionDecl *OrigFD = FD->getInstantiatedFromMemberFunction()) {
14344  // A merged copy of the same function, instantiated as a member of
14345  // the same class, is OK.
14346  if (declaresSameEntity(OrigFD, OrigDef) &&
14347  declaresSameEntity(cast<Decl>(Definition->getLexicalDeclContext()),
14348  cast<Decl>(FD->getLexicalDeclContext())))
14349  return;
14350  }
14351  }
14352  }
14353 
14354  if (canRedefineFunction(Definition, getLangOpts()))
14355  return;
14356 
14357  // Don't emit an error when this is redefinition of a typo-corrected
14358  // definition.
14359  if (TypoCorrectedFunctionDefinitions.count(Definition))
14360  return;
14361 
14362  // If we don't have a visible definition of the function, and it's inline or
14363  // a template, skip the new definition.
14364  if (SkipBody && !hasVisibleDefinition(Definition) &&
14365  (Definition->getFormalLinkage() == InternalLinkage ||
14366  Definition->isInlined() ||
14367  Definition->getDescribedFunctionTemplate() ||
14368  Definition->getNumTemplateParameterLists())) {
14369  SkipBody->ShouldSkip = true;
14370  SkipBody->Previous = const_cast<FunctionDecl*>(Definition);
14371  if (auto *TD = Definition->getDescribedFunctionTemplate())
14372  makeMergedDefinitionVisible(TD);
14373  makeMergedDefinitionVisible(const_cast<FunctionDecl*>(Definition));
14374  return;
14375  }
14376 
14377  if (getLangOpts().GNUMode && Definition->isInlineSpecified() &&
14378  Definition->getStorageClass() == SC_Extern)
14379  Diag(FD->getLocation(), diag::err_redefinition_extern_inline)
14380  << FD << getLangOpts().CPlusPlus;
14381  else
14382  Diag(FD->getLocation(), diag::err_redefinition) << FD;
14383 
14384  Diag(Definition->getLocation(), diag::note_previous_definition);
14385  FD->setInvalidDecl();
14386 }
14387 
14388 static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator,
14389  Sema &S) {
14390  CXXRecordDecl *const LambdaClass = CallOperator->getParent();
14391 
14392  LambdaScopeInfo *LSI = S.PushLambdaScope();
14393  LSI->CallOperator = CallOperator;
14394  LSI->Lambda = LambdaClass;
14395  LSI->ReturnType = CallOperator->getReturnType();
14396  const LambdaCaptureDefault LCD = LambdaClass->getLambdaCaptureDefault();
14397 
14398  if (LCD == LCD_None)
14400  else if (LCD == LCD_ByCopy)
14402  else if (LCD == LCD_ByRef)
14404  DeclarationNameInfo DNI = CallOperator->getNameInfo();
14405 
14407  LSI->Mutable = !CallOperator->isConst();
14408 
14409  // Add the captures to the LSI so they can be noted as already
14410  // captured within tryCaptureVar.
14411  auto I = LambdaClass->field_begin();
14412  for (const auto &C : LambdaClass->captures()) {
14413  if (C.capturesVariable()) {
14414  VarDecl *VD = C.getCapturedVar();
14415  if (VD->isInitCapture())
14417  const bool ByRef = C.getCaptureKind() == LCK_ByRef;
14418  LSI->addCapture(VD, /*IsBlock*/false, ByRef,
14419  /*RefersToEnclosingVariableOrCapture*/true, C.getLocation(),
14420  /*EllipsisLoc*/C.isPackExpansion()
14421  ? C.getEllipsisLoc() : SourceLocation(),
14422  I->getType(), /*Invalid*/false);
14423 
14424  } else if (C.capturesThis()) {
14425  LSI->addThisCapture(/*Nested*/ false, C.getLocation(), I->getType(),
14426  C.getCaptureKind() == LCK_StarThis);
14427  } else {
14428  LSI->addVLATypeCapture(C.getLocation(), I->getCapturedVLAType(),
14429  I->getType());
14430  }
14431  ++I;
14432  }
14433 }
14434 
14436  SkipBodyInfo *SkipBody) {
14437  if (!D) {
14438  // Parsing the function declaration failed in some way. Push on a fake scope
14439  // anyway so we can try to parse the function body.
14440  PushFunctionScope();
14441  PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
14442  return D;
14443  }
14444 
14445  FunctionDecl *FD = nullptr;
14446 
14447  if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(D))
14448  FD = FunTmpl->getTemplatedDecl();
14449  else
14450  FD = cast<FunctionDecl>(D);
14451 
14452  // Do not push if it is a lambda because one is already pushed when building
14453  // the lambda in ActOnStartOfLambdaDefinition().
14454  if (!isLambdaCallOperator(FD))
14455  PushExpressionEvaluationContext(
14456  FD->isConsteval() ? ExpressionEvaluationContext::ConstantEvaluated
14457  : ExprEvalContexts.back().Context);
14458 
14459  // Check for defining attributes before the check for redefinition.
14460  if (const auto *Attr = FD->getAttr<AliasAttr>()) {
14461  Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 0;
14462  FD->dropAttr<AliasAttr>();
14463  FD->setInvalidDecl();
14464  }
14465  if (const auto *Attr = FD->getAttr<IFuncAttr>()) {
14466  Diag(Attr->getLocation(), diag::err_alias_is_definition) << FD << 1;
14467  FD->dropAttr<IFuncAttr>();
14468  FD->setInvalidDecl();
14469  }
14470 
14471  if (auto *Ctor = dyn_cast<CXXConstructorDecl>(FD)) {
14472  if (Ctor->getTemplateSpecializationKind() == TSK_ExplicitSpecialization &&
14473  Ctor->isDefaultConstructor() &&
14474  Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14475  // If this is an MS ABI dllexport default constructor, instantiate any
14476  // default arguments.
14477  InstantiateDefaultCtorDefaultArgs(Ctor);
14478  }
14479  }
14480 
14481  // See if this is a redefinition. If 'will have body' (or similar) is already
14482  // set, then these checks were already performed when it was set.
14483  if (!FD->willHaveBody() && !FD->isLateTemplateParsed() &&
14485  CheckForFunctionRedefinition(FD, nullptr, SkipBody);
14486 
14487  // If we're skipping the body, we're done. Don't enter the scope.
14488  if (SkipBody && SkipBody->ShouldSkip)
14489  return D;
14490  }
14491 
14492  // Mark this function as "will have a body eventually". This lets users to
14493  // call e.g. isInlineDefinitionExternallyVisible while we're still parsing
14494  // this function.
14495  FD->setWillHaveBody();
14496 
14497  // If we are instantiating a generic lambda call operator, push
14498  // a LambdaScopeInfo onto the function stack. But use the information
14499  // that's already been calculated (ActOnLambdaExpr) to prime the current
14500  // LambdaScopeInfo.
14501  // When the template operator is being specialized, the LambdaScopeInfo,
14502  // has to be properly restored so that tryCaptureVariable doesn't try
14503  // and capture any new variables. In addition when calculating potential
14504  // captures during transformation of nested lambdas, it is necessary to
14505  // have the LSI properly restored.
14507  assert(inTemplateInstantiation() &&
14508  "There should be an active template instantiation on the stack "
14509  "when instantiating a generic lambda!");
14510  RebuildLambdaScopeInfo(cast<CXXMethodDecl>(D), *this);
14511  } else {
14512  // Enter a new function scope
14513  PushFunctionScope();
14514  }
14515 
14516  // Builtin functions cannot be defined.
14517  if (unsigned BuiltinID = FD->getBuiltinID()) {
14518  if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID) &&
14519  !Context.BuiltinInfo.isPredefinedRuntimeFunction(BuiltinID)) {
14520  Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
14521  FD->setInvalidDecl();
14522  }
14523  }
14524 
14525  // The return type of a function definition must be complete
14526  // (C99 6.9.1p3, C++ [dcl.fct]p6).
14527  QualType ResultType = FD->getReturnType();
14528  if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
14529  !FD->isInvalidDecl() &&
14530  RequireCompleteType(FD->getLocation(), ResultType,
14531  diag::err_func_def_incomplete_result))
14532  FD->setInvalidDecl();
14533 
14534  if (FnBodyScope)
14535  PushDeclContext(FnBodyScope, FD);
14536 
14537  // Check the validity of our function parameters
14538  CheckParmsForFunctionDef(FD->parameters(),
14539  /*CheckParameterNames=*/true);
14540 
14541  // Add non-parameter declarations already in the function to the current
14542  // scope.
14543  if (FnBodyScope) {
14544  for (Decl *NPD : FD->decls()) {
14545  auto *NonParmDecl = dyn_cast<NamedDecl>(NPD);
14546  if (!NonParmDecl)
14547  continue;
14548  assert(!isa<ParmVarDecl>(NonParmDecl) &&
14549  "parameters should not be in newly created FD yet");
14550 
14551  // If the decl has a name, make it accessible in the current scope.
14552  if (NonParmDecl->getDeclName())
14553  PushOnScopeChains(NonParmDecl, FnBodyScope, /*AddToContext=*/false);
14554 
14555  // Similarly, dive into enums and fish their constants out, making them
14556  // accessible in this scope.
14557  if (auto *ED = dyn_cast<EnumDecl>(NonParmDecl)) {
14558  for (auto *EI : ED->enumerators())
14559  PushOnScopeChains(EI, FnBodyScope, /*AddToContext=*/false);
14560  }
14561  }
14562  }
14563 
14564  // Introduce our parameters into the function scope
14565  for (auto Param : FD->parameters()) {
14566  Param->setOwningFunction(FD);
14567 
14568  // If this has an identifier, add it to the scope stack.
14569  if (Param->getIdentifier() && FnBodyScope) {
14570  CheckShadow(FnBodyScope, Param);
14571 
14572  PushOnScopeChains(Param, FnBodyScope);
14573  }
14574  }
14575 
14576  // Ensure that the function's exception specification is instantiated.
14577  if (const FunctionProtoType *FPT = FD->getType()->getAs<FunctionProtoType>())
14578  ResolveExceptionSpec(D->getLocation(), FPT);
14579 
14580  // dllimport cannot be applied to non-inline function definitions.
14581  if (FD->hasAttr<DLLImportAttr>() && !FD->isInlined() &&
14582  !FD->isTemplateInstantiation()) {
14583  assert(!FD->hasAttr<DLLExportAttr>());
14584  Diag(FD->getLocation(), diag::err_attribute_dllimport_function_definition);
14585  FD->setInvalidDecl();
14586  return D;
14587  }
14588  // We want to attach documentation to original Decl (which might be
14589  // a function template).
14590  ActOnDocumentableDecl(D);
14591  if (getCurLexicalContext()->isObjCContainer() &&
14592  getCurLexicalContext()->getDeclKind() != Decl::ObjCCategoryImpl &&
14593  getCurLexicalContext()->getDeclKind() != Decl::ObjCImplementation)
14594  Diag(FD->getLocation(), diag::warn_function_def_in_objc_container);
14595 
14596  return D;
14597 }
14598 
14599 /// Given the set of return statements within a function body,
14600 /// compute the variables that are subject to the named return value
14601 /// optimization.
14602 ///
14603 /// Each of the variables that is subject to the named return value
14604 /// optimization will be marked as NRVO variables in the AST, and any
14605 /// return statement that has a marked NRVO variable as its NRVO candidate can
14606 /// use the named return value optimization.
14607 ///
14608 /// This function applies a very simplistic algorithm for NRVO: if every return
14609 /// statement in the scope of a variable has the same NRVO candidate, that
14610 /// candidate is an NRVO variable.
14612  ReturnStmt **Returns = Scope->Returns.data();
14613 
14614  for (unsigned I = 0, E = Scope->Returns.size(); I != E; ++I) {
14615  if (const VarDecl *NRVOCandidate = Returns[I]->getNRVOCandidate()) {
14616  if (!NRVOCandidate->isNRVOVariable())
14617  Returns[I]->setNRVOCandidate(nullptr);
14618  }
14619  }
14620 }
14621 
14623  // We can't delay parsing the body of a constexpr function template (yet).
14625  return false;
14626 
14627  // We can't delay parsing the body of a function template with a deduced
14628  // return type (yet).
14629  if (D.getDeclSpec().hasAutoTypeSpec()) {
14630  // If the placeholder introduces a non-deduced trailing return type,
14631  // we can still delay parsing it.
14632  if (D.getNumTypeObjects()) {
14633  const auto &Outer = D.getTypeObject(D.getNumTypeObjects() - 1);
14634  if (Outer.Kind == DeclaratorChunk::Function &&
14635  Outer.Fun.hasTrailingReturnType()) {
14636  QualType Ty = GetTypeFromParser(Outer.Fun.getTrailingReturnType());
14637  return Ty.isNull() || !Ty->isUndeducedType();
14638  }
14639  }
14640  return false;
14641  }
14642 
14643  return true;
14644 }
14645 
14647  // We cannot skip the body of a function (or function template) which is
14648  // constexpr, since we may need to evaluate its body in order to parse the
14649  // rest of the file.
14650  // We cannot skip the body of a function with an undeduced return type,
14651  // because any callers of that function need to know the type.
14652  if (const FunctionDecl *FD = D->getAsFunction()) {
14653  if (FD->isConstexpr())
14654  return false;
14655  // We can't simply call Type::isUndeducedType here, because inside template
14656  // auto can be deduced to a dependent type, which is not considered
14657  // "undeduced".
14658  if (FD->getReturnType()->getContainedDeducedType())
14659  return false;
14660  }
14661  return Consumer.shouldSkipFunctionBody(D);
14662 }
14663 
14665  if (!Decl)
14666  return nullptr;
14667  if (FunctionDecl *FD = Decl->getAsFunction())
14668  FD->setHasSkippedBody();
14669  else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(Decl))
14670  MD->setHasSkippedBody();
14671  return Decl;
14672 }
14673 
14675  return ActOnFinishFunctionBody(D, BodyArg, false);
14676 }
14677 
14678 /// RAII object that pops an ExpressionEvaluationContext when exiting a function
14679 /// body.
14681 public:
14682  ExitFunctionBodyRAII(Sema &S, bool IsLambda) : S(S), IsLambda(IsLambda) {}
14684  if (!IsLambda)
14686  }
14687 
14688 private:
14689  Sema &S;
14690  bool IsLambda = false;
14691 };
14692 
14694  llvm::DenseMap<const BlockDecl *, bool> EscapeInfo;
14695 
14696  auto IsOrNestedInEscapingBlock = [&](const BlockDecl *BD) {
14697  if (EscapeInfo.count(BD))
14698  return EscapeInfo[BD];
14699 
14700  bool R = false;
14701  const BlockDecl *CurBD = BD;
14702 
14703  do {
14704  R = !CurBD->doesNotEscape();
14705  if (R)
14706  break;
14707  CurBD = CurBD->getParent()->getInnermostBlockDecl();
14708  } while (CurBD);
14709 
14710  return EscapeInfo[BD] = R;
14711  };
14712 
14713  // If the location where 'self' is implicitly retained is inside a escaping
14714  // block, emit a diagnostic.
14715  for (const std::pair<SourceLocation, const BlockDecl *> &P :
14717  if (IsOrNestedInEscapingBlock(P.second))
14718  S.Diag(P.first, diag::warn_implicitly_retains_self)
14719  << FixItHint::CreateInsertion(P.first, "self->");
14720 }
14721 
14723  bool IsInstantiation) {
14724  FunctionScopeInfo *FSI = getCurFunction();
14725  FunctionDecl *FD = dcl ? dcl->getAsFunction() : nullptr;
14726 
14727  if (FSI->UsesFPIntrin && FD && !FD->hasAttr<StrictFPAttr>())
14728  FD->addAttr(StrictFPAttr::CreateImplicit(Context));
14729 
14730  sema::AnalysisBasedWarnings::Policy WP = AnalysisWarnings.getDefaultPolicy();
14731  sema::AnalysisBasedWarnings::Policy *ActivePolicy = nullptr;
14732 
14733  if (getLangOpts().Coroutines && FSI->isCoroutine())
14734  CheckCompletedCoroutineBody(FD, Body);
14735 
14736  {
14737  // Do not call PopExpressionEvaluationContext() if it is a lambda because
14738  // one is already popped when finishing the lambda in BuildLambdaExpr().
14739  // This is meant to pop the context added in ActOnStartOfFunctionDef().
14740  ExitFunctionBodyRAII ExitRAII(*this, isLambdaCallOperator(FD));
14741 
14742  if (FD) {
14743  FD->setBody(Body);
14744  FD->setWillHaveBody(false);
14745 
14746  if (getLangOpts().CPlusPlus14) {
14747  if (!FD->isInvalidDecl() && Body && !FD->isDependentContext() &&
14748  FD->getReturnType()->isUndeducedType()) {
14749  // For a function with a deduced result type to return void,
14750  // the result type as written must be 'auto' or 'decltype(auto)',
14751  // possibly cv-qualified or constrained, but not ref-qualified.
14752  if (!FD->getReturnType()->getAs<AutoType>()) {
14753  Diag(dcl->getLocation(), diag::err_auto_fn_no_return_but_not_auto)
14754  << FD->getReturnType();
14755  FD->setInvalidDecl();
14756  } else {
14757  // Falling off the end of the function is the same as 'return;'.
14758  Expr *Dummy = nullptr;
14759  if (DeduceFunctionTypeFromReturnExpr(
14760  FD, dcl->getLocation(), Dummy,
14761  FD->getReturnType()->getAs<AutoType>()))
14762  FD->setInvalidDecl();
14763  }
14764  }
14765  } else if (getLangOpts().CPlusPlus11 && isLambdaCallOperator(FD)) {
14766  // In C++11, we don't use 'auto' deduction rules for lambda call
14767  // operators because we don't support return type deduction.
14768  auto *LSI = getCurLambda();
14769  if (LSI->HasImplicitReturnType) {
14770  deduceClosureReturnType(*LSI);
14771 
14772  // C++11 [expr.prim.lambda]p4:
14773  // [...] if there are no return statements in the compound-statement
14774  // [the deduced type is] the type void
14775  QualType RetType =
14776  LSI->ReturnType.isNull() ? Context.VoidTy : LSI->ReturnType;
14777 
14778  // Update the return type to the deduced type.
14779  const auto *Proto = FD->getType()->castAs<FunctionProtoType>();
14780  FD->setType(Context.getFunctionType(RetType, Proto->getParamTypes(),
14781  Proto->getExtProtoInfo()));
14782  }
14783  }
14784 
14785  // If the function implicitly returns zero (like 'main') or is naked,
14786  // don't complain about missing return statements.
14787  if (FD->hasImplicitReturnZero() || FD->hasAttr<NakedAttr>())
14789 
14790  // MSVC permits the use of pure specifier (=0) on function definition,
14791  // defined at class scope, warn about this non-standard construct.
14792  if (getLangOpts().MicrosoftExt && FD->isPure() && !FD->isOutOfLine())
14793  Diag(FD->getLocation(), diag::ext_pure_function_definition);
14794 
14795  if (!FD->isInvalidDecl()) {
14796  // Don't diagnose unused parameters of defaulted, deleted or naked
14797  // functions.
14798  if (!FD->isDeleted() && !FD->isDefaulted() && !FD->hasSkippedBody() &&
14799  !FD->hasAttr<NakedAttr>())
14800  DiagnoseUnusedParameters(FD->parameters());
14801  DiagnoseSizeOfParametersAndReturnValue(FD->parameters(),
14802  FD->getReturnType(), FD);
14803 
14804  // If this is a structor, we need a vtable.
14805  if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(FD))
14806  MarkVTableUsed(FD->getLocation(), Constructor->getParent());
14807  else if (CXXDestructorDecl *Destructor =
14808  dyn_cast<CXXDestructorDecl>(FD))
14809  MarkVTableUsed(FD->getLocation(), Destructor->getParent());
14810 
14811  // Try to apply the named return value optimization. We have to check
14812  // if we can do this here because lambdas keep return statements around
14813  // to deduce an implicit return type.
14814  if (FD->getReturnType()->isRecordType() &&
14815  (!getLangOpts().CPlusPlus || !FD->isDependentContext()))
14816  computeNRVO(Body, FSI);
14817  }
14818 
14819  // GNU warning -Wmissing-prototypes:
14820  // Warn if a global function is defined without a previous
14821  // prototype declaration. This warning is issued even if the
14822  // definition itself provides a prototype. The aim is to detect
14823  // global functions that fail to be declared in header files.
14824  const FunctionDecl *PossiblePrototype = nullptr;
14825  if (ShouldWarnAboutMissingPrototype(FD, PossiblePrototype)) {
14826  Diag(FD->getLocation(), diag::warn_missing_prototype) << FD;
14827 
14828  if (PossiblePrototype) {
14829  // We found a declaration that is not a prototype,
14830  // but that could be a zero-parameter prototype
14831  if (TypeSourceInfo *TI = PossiblePrototype->getTypeSourceInfo()) {
14832  TypeLoc TL = TI->getTypeLoc();
14834  Diag(PossiblePrototype->getLocation(),
14835  diag::note_declaration_not_a_prototype)
14836  << (FD->getNumParams() != 0)
14837  << (FD->getNumParams() == 0 ? FixItHint::CreateInsertion(
14838  FTL.getRParenLoc(), "void")
14839  : FixItHint{});
14840  }
14841  } else {
14842  // Returns true if the token beginning at this Loc is `const`.
14843  auto isLocAtConst = [&](SourceLocation Loc, const SourceManager &SM,
14844  const LangOptions &LangOpts) {
14845  std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
14846  if (LocInfo.first.isInvalid())
14847  return false;
14848 
14849  bool Invalid = false;
14850  StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
14851  if (Invalid)
14852  return false;
14853 
14854  if (LocInfo.second > Buffer.size())
14855  return false;
14856 
14857  const char *LexStart = Buffer.data() + LocInfo.second;
14858  StringRef StartTok(LexStart, Buffer.size() - LocInfo.second);
14859 
14860  return StartTok.consume_front("const") &&
14861  (StartTok.empty() || isWhitespace(StartTok[0]) ||
14862  StartTok.startswith("/*") || StartTok.startswith("//"));
14863  };
14864 
14865  auto findBeginLoc = [&]() {
14866  // If the return type has `const` qualifier, we want to insert
14867  // `static` before `const` (and not before the typename).
14868  if ((FD->getReturnType()->isAnyPointerType() &&
14870  FD->getReturnType().isConstQualified()) {
14871  // But only do this if we can determine where the `const` is.
14872 
14873  if (isLocAtConst(FD->getBeginLoc(), getSourceManager(),
14874  getLangOpts()))
14875 
14876  return FD->getBeginLoc();
14877  }
14878  return FD->getTypeSpecStartLoc();
14879  };
14880  Diag(FD->getTypeSpecStartLoc(),
14881  diag::note_static_for_internal_linkage)
14882  << /* function */ 1
14883  << (FD->getStorageClass() == SC_None
14884  ? FixItHint::CreateInsertion(findBeginLoc(), "static ")
14885  : FixItHint{});
14886  }
14887 
14888  // GNU warning -Wstrict-prototypes
14889  // Warn if K&R function is defined without a previous declaration.
14890  // This warning is issued only if the definition itself does not
14891  // provide a prototype. Only K&R definitions do not provide a
14892  // prototype.
14893  if (!FD->hasWrittenPrototype()) {
14894  TypeSourceInfo *TI = FD->getTypeSourceInfo();
14895  TypeLoc TL = TI->getTypeLoc();
14897  Diag(FTL.getLParenLoc(), diag::warn_strict_prototypes) << 2;
14898  }
14899  }
14900 
14901  // Warn on CPUDispatch with an actual body.
14902  if (FD->isMultiVersion() && FD->hasAttr<CPUDispatchAttr>() && Body)
14903  if (const auto *CmpndBody = dyn_cast<CompoundStmt>(Body))
14904  if (!CmpndBody->body_empty())
14905  Diag(CmpndBody->body_front()->getBeginLoc(),
14906  diag::warn_dispatch_body_ignored);
14907 
14908  if (auto *MD = dyn_cast<CXXMethodDecl>(FD)) {
14909  const CXXMethodDecl *KeyFunction;
14910  if (MD->isOutOfLine() && (MD = MD->getCanonicalDecl()) &&
14911  MD->isVirtual() &&
14912  (KeyFunction = Context.getCurrentKeyFunction(MD->getParent())) &&
14913  MD == KeyFunction->getCanonicalDecl()) {
14914  // Update the key-function state if necessary for this ABI.
14915  if (FD->isInlined() &&
14917  Context.setNonKeyFunction(MD);
14918 
14919  // If the newly-chosen key function is already defined, then we
14920  // need to mark the vtable as used retroactively.
14921  KeyFunction = Context.getCurrentKeyFunction(MD->getParent());
14922  const FunctionDecl *Definition;
14923  if (KeyFunction && KeyFunction->isDefined(Definition))
14924  MarkVTableUsed(Definition->getLocation(), MD->getParent(), true);
14925  } else {
14926  // We just defined they key function; mark the vtable as used.
14927  MarkVTableUsed(FD->getLocation(), MD->getParent(), true);
14928  }
14929  }
14930  }
14931 
14932  assert(
14933  (FD == getCurFunctionDecl() || getCurLambda()->CallOperator == FD) &&
14934  "Function parsing confused");
14935  } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
14936  assert(MD == getCurMethodDecl() && "Method parsing confused");
14937  MD->setBody(Body);
14938  if (!MD->isInvalidDecl()) {
14939  DiagnoseSizeOfParametersAndReturnValue(MD->parameters(),
14940  MD->getReturnType(), MD);
14941 
14942  if (Body)
14943  computeNRVO(Body, FSI);
14944  }
14945  if (FSI->ObjCShouldCallSuper) {
14946  Diag(MD->getEndLoc(), diag::warn_objc_missing_super_call)
14947  << MD->getSelector().getAsString();
14948  FSI->ObjCShouldCallSuper = false;
14949  }
14951  const ObjCMethodDecl *InitMethod = nullptr;
14952  bool isDesignated =
14953  MD->isDesignatedInitializerForTheInterface(&InitMethod);
14954  assert(isDesignated && InitMethod);
14955  (void)isDesignated;
14956 
14957  auto superIsNSObject = [&](const ObjCMethodDecl *MD) {
14958  auto IFace = MD->getClassInterface();
14959  if (!IFace)
14960  return false;
14961  auto SuperD = IFace->getSuperClass();
14962  if (!SuperD)
14963  return false;
14964  return SuperD->getIdentifier() ==
14965  NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject);
14966  };
14967  // Don't issue this warning for unavailable inits or direct subclasses
14968  // of NSObject.
14969  if (!MD->isUnavailable() && !superIsNSObject(MD)) {
14970  Diag(MD->getLocation(),
14971  diag::warn_objc_designated_init_missing_super_call);
14972  Diag(InitMethod->getLocation(),
14973  diag::note_objc_designated_init_marked_here);
14974  }
14975  FSI->ObjCWarnForNoDesignatedInitChain = false;
14976  }
14977  if (FSI->ObjCWarnForNoInitDelegation) {
14978  // Don't issue this warning for unavaialable inits.
14979  if (!MD->isUnavailable())
14980  Diag(MD->getLocation(),
14981  diag::warn_objc_secondary_init_missing_init_call);
14982  FSI->ObjCWarnForNoInitDelegation = false;
14983  }
14984 
14986  } else {
14987  // Parsing the function declaration failed in some way. Pop the fake scope
14988  // we pushed on.
14989  PopFunctionScopeInfo(ActivePolicy, dcl);
14990  return nullptr;
14991  }
14992 
14993  if (Body && FSI->HasPotentialAvailabilityViolations)
14994  DiagnoseUnguardedAvailabilityViolations(dcl);
14995 
14996  assert(!FSI->ObjCShouldCallSuper &&
14997  "This should only be set for ObjC methods, which should have been "
14998  "handled in the block above.");
14999 
15000  // Verify and clean out per-function state.
15001  if (Body && (!FD || !FD->isDefaulted())) {
15002  // C++ constructors that have function-try-blocks can't have return
15003  // statements in the handlers of that block. (C++ [except.handle]p14)
15004  // Verify this.
15005  if (FD && isa<CXXConstructorDecl>(FD) && isa<CXXTryStmt>(Body))
15006  DiagnoseReturnInConstructorExceptionHandler(cast<CXXTryStmt>(Body));
15007 
15008  // Verify that gotos and switch cases don't jump into scopes illegally.
15009  if (FSI->NeedsScopeChecking() && !PP.isCodeCompletionEnabled())
15010  DiagnoseInvalidJumps(Body);
15011 
15012  if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(dcl)) {
15013  if (!Destructor->getParent()->isDependentType())
15014  CheckDestructor(Destructor);
15015 
15016  MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
15017  Destructor->getParent());
15018  }
15019 
15020  // If any errors have occurred, clear out any temporaries that may have
15021  // been leftover. This ensures that these temporaries won't be picked up
15022  // for deletion in some later function.
15023  if (hasUncompilableErrorOccurred() ||
15024  getDiagnostics().getSuppressAllDiagnostics()) {
15025  DiscardCleanupsInEvaluationContext();
15026  }
15027  if (!hasUncompilableErrorOccurred() && !isa<FunctionTemplateDecl>(dcl)) {
15028  // Since the body is valid, issue any analysis-based warnings that are
15029  // enabled.
15030  ActivePolicy = &WP;
15031  }
15032 
15033  if (!IsInstantiation && FD && FD->isConstexpr() && !FD->isInvalidDecl() &&
15034  !CheckConstexprFunctionDefinition(FD, CheckConstexprKind::Diagnose))
15035  FD->setInvalidDecl();
15036 
15037  if (FD && FD->hasAttr<NakedAttr>()) {
15038  for (const Stmt *S : Body->children()) {
15039  // Allow local register variables without initializer as they don't
15040  // require prologue.
15041  bool RegisterVariables = false;
15042  if (auto *DS = dyn_cast<DeclStmt>(S)) {
15043  for (const auto *Decl : DS->decls()) {
15044  if (const auto *Var = dyn_cast<VarDecl>(Decl)) {
15045  RegisterVariables =
15046  Var->hasAttr<AsmLabelAttr>() && !Var->hasInit();
15047  if (!RegisterVariables)
15048  break;
15049  }
15050  }
15051  }
15052  if (RegisterVariables)
15053  continue;
15054  if (!isa<AsmStmt>(S) && !isa<NullStmt>(S)) {
15055  Diag(S->getBeginLoc(), diag::err_non_asm_stmt_in_naked_function);
15056  Diag(FD->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
15057  FD->setInvalidDecl();
15058  break;
15059  }
15060  }
15061  }
15062 
15063  assert(ExprCleanupObjects.size() ==
15064  ExprEvalContexts.back().NumCleanupObjects &&
15065  "Leftover temporaries in function");
15066  assert(!Cleanup.exprNeedsCleanups() &&
15067  "Unaccounted cleanups in function");
15068  assert(MaybeODRUseExprs.empty() &&
15069  "Leftover expressions for odr-use checking");
15070  }
15071  } // Pops the ExitFunctionBodyRAII scope, which needs to happen before we pop
15072  // the declaration context below. Otherwise, we're unable to transform
15073  // 'this' expressions when transforming immediate context functions.
15074 
15075  if (!IsInstantiation)
15076  PopDeclContext();
15077 
15078  PopFunctionScopeInfo(ActivePolicy, dcl);
15079  // If any errors have occurred, clear out any temporaries that may have
15080  // been leftover. This ensures that these temporaries won't be picked up for
15081  // deletion in some later function.
15082  if (hasUncompilableErrorOccurred()) {
15083  DiscardCleanupsInEvaluationContext();
15084  }
15085 
15086  if (FD && ((LangOpts.OpenMP && (LangOpts.OpenMPIsDevice ||
15087  !LangOpts.OMPTargetTriples.empty())) ||
15088  LangOpts.CUDA || LangOpts.SYCLIsDevice)) {
15089  auto ES = getEmissionStatus(FD);
15092  DeclsToCheckForDeferredDiags.insert(FD);
15093  }
15094 
15095  if (FD && !FD->isDeleted())
15096  checkTypeSupport(FD->getType(), FD->getLocation(), FD);
15097 
15098  return dcl;
15099 }
15100 
15101 /// When we finish delayed parsing of an attribute, we must attach it to the
15102 /// relevant Decl.
15104  ParsedAttributes &Attrs) {
15105  // Always attach attributes to the underlying decl.
15106  if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
15107  D = TD->getTemplatedDecl();
15108  ProcessDeclAttributeList(S, D, Attrs);
15109 
15110  if (CXXMethodDecl *Method = dyn_cast_or_null<CXXMethodDecl>(D))
15111  if (Method->isStatic())
15112  checkThisInStaticMemberFunctionAttributes(Method);
15113 }
15114 
15115 /// ImplicitlyDefineFunction - An undeclared identifier was used in a function
15116 /// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
15118  IdentifierInfo &II, Scope *S) {
15119  // Find the scope in which the identifier is injected and the corresponding
15120  // DeclContext.
15121  // FIXME: C89 does not say what happens if there is no enclosing block scope.
15122  // In that case, we inject the declaration into the translation unit scope
15123  // instead.
15124  Scope *BlockScope = S;
15125  while (!BlockScope->isCompoundStmtScope() && BlockScope->getParent())
15126  BlockScope = BlockScope->getParent();
15127 
15128  Scope *ContextScope = BlockScope;
15129  while (!ContextScope->getEntity())
15130  ContextScope = ContextScope->getParent();
15131  ContextRAII SavedContext(*this, ContextScope->getEntity());
15132 
15133  // Before we produce a declaration for an implicitly defined
15134  // function, see whether there was a locally-scoped declaration of
15135  // this name as a function or variable. If so, use that
15136  // (non-visible) declaration, and complain about it.
15137  NamedDecl *ExternCPrev = findLocallyScopedExternCDecl(&II);
15138  if (ExternCPrev) {
15139  // We still need to inject the function into the enclosing block scope so
15140  // that later (non-call) uses can see it.
15141  PushOnScopeChains(ExternCPrev, BlockScope, /*AddToContext*/false);
15142 
15143  // C89 footnote 38:
15144  // If in fact it is not defined as having type "function returning int",
15145  // the behavior is undefined.
15146  if (!isa<FunctionDecl>(ExternCPrev) ||
15147  !Context.typesAreCompatible(
15148  cast<FunctionDecl>(ExternCPrev)->getType(),
15149  Context.getFunctionNoProtoType(Context.IntTy))) {
15150  Diag(Loc, diag::ext_use_out_of_scope_declaration)
15151  << ExternCPrev << !getLangOpts().C99;
15152  Diag(ExternCPrev->getLocation(), diag::note_previous_declaration);
15153  return ExternCPrev;
15154  }
15155  }
15156 
15157  // Extension in C99. Legal in C90, but warn about it.
15158  unsigned diag_id;
15159  if (II.getName().startswith("__builtin_"))
15160  diag_id = diag::warn_builtin_unknown;
15161  // OpenCL v2.0 s6.9.u - Implicit function declaration is not supported.
15162  else if (getLangOpts().OpenCL)
15163  diag_id = diag::err_opencl_implicit_function_decl;
15164  else if (getLangOpts().C99)
15165  diag_id = diag::ext_implicit_function_decl;
15166  else
15167  diag_id = diag::warn_implicit_function_decl;
15168 
15169  TypoCorrection Corrected;
15170  // Because typo correction is expensive, only do it if the implicit
15171  // function declaration is going to be treated as an error.
15172  //
15173  // Perform the corection before issuing the main diagnostic, as some consumers
15174  // use typo-correction callbacks to enhance the main diagnostic.
15175  if (S && !ExternCPrev &&
15176  (Diags.getDiagnosticLevel(diag_id, Loc) >= DiagnosticsEngine::Error)) {
15178  Corrected = CorrectTypo(DeclarationNameInfo(&II, Loc), LookupOrdinaryName,
15179  S, nullptr, CCC, CTK_NonError);
15180  }
15181 
15182  Diag(Loc, diag_id) << &II;
15183  if (Corrected)
15184  diagnoseTypo(Corrected, PDiag(diag::note_function_suggestion),
15185  /*ErrorRecovery*/ false);
15186 
15187  // If we found a prior declaration of this function, don't bother building
15188  // another one. We've already pushed that one into scope, so there's nothing
15189  // more to do.
15190  if (ExternCPrev)
15191  return ExternCPrev;
15192 
15193  // Set a Declarator for the implicit definition: int foo();
15194  const char *Dummy;
15195  AttributeFactory attrFactory;
15196  DeclSpec DS(attrFactory);
15197  unsigned DiagID;
15198  bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy, DiagID,
15199  Context.getPrintingPolicy());
15200  (void)Error; // Silence warning.
15201  assert(!Error && "Error setting up implicit decl!");
15202  SourceLocation NoLoc;
15204  D.AddTypeInfo(DeclaratorChunk::getFunction(/*HasProto=*/false,
15205  /*IsAmbiguous=*/false,
15206  /*LParenLoc=*/NoLoc,
15207  /*Params=*/nullptr,
15208  /*NumParams=*/0,
15209  /*EllipsisLoc=*/NoLoc,
15210  /*RParenLoc=*/NoLoc,
15211  /*RefQualifierIsLvalueRef=*/true,
15212  /*RefQualifierLoc=*/NoLoc,
15213  /*MutableLoc=*/NoLoc, EST_None,
15214  /*ESpecRange=*/SourceRange(),
15215  /*Exceptions=*/nullptr,
15216  /*ExceptionRanges=*/nullptr,
15217  /*NumExceptions=*/0,
15218  /*NoexceptExpr=*/nullptr,
15219  /*ExceptionSpecTokens=*/nullptr,
15220  /*DeclsInPrototype=*/None, Loc,
15221  Loc, D),
15222  std::move(DS.getAttributes()), SourceLocation());
15223  D.SetIdentifier(&II, Loc);
15224 
15225  // Insert this function into the enclosing block scope.
15226  FunctionDecl *FD = cast<FunctionDecl>(ActOnDeclarator(BlockScope, D));
15227  FD->setImplicit();
15228 
15229  AddKnownFunctionAttributes(FD);
15230 
15231  return FD;
15232 }
15233 
15234 /// If this function is a C++ replaceable global allocation function
15235 /// (C++2a [basic.stc.dynamic.allocation], C++2a [new.delete]),
15236 /// adds any function attributes that we know a priori based on the standard.
15237 ///
15238 /// We need to check for duplicate attributes both here and where user-written
15239 /// attributes are applied to declarations.
15241  FunctionDecl *FD) {
15242  if (FD->isInvalidDecl())
15243  return;
15244 
15245  if (FD->getDeclName().getCXXOverloadedOperator() != OO_New &&
15246  FD->getDeclName().getCXXOverloadedOperator() != OO_Array_New)
15247  return;
15248 
15249  Optional<unsigned> AlignmentParam;
15250  bool IsNothrow = false;
15251  if (!FD->isReplaceableGlobalAllocationFunction(&AlignmentParam, &IsNothrow))
15252  return;
15253 
15254  // C++2a [basic.stc.dynamic.allocation]p4:
15255  // An allocation function that has a non-throwing exception specification
15256  // indicates failure by returning a null pointer value. Any other allocation
15257  // function never returns a null pointer value and indicates failure only by
15258  // throwing an exception [...]
15259  if (!IsNothrow && !FD->hasAttr<ReturnsNonNullAttr>())
15260  FD->addAttr(ReturnsNonNullAttr::CreateImplicit(Context, FD->getLocation()));
15261 
15262  // C++2a [basic.stc.dynamic.allocation]p2:
15263  // An allocation function attempts to allocate the requested amount of
15264  // storage. [...] If the request succeeds, the value returned by a
15265  // replaceable allocation function is a [...] pointer value p0 different
15266  // from any previously returned value p1 [...]
15267  //
15268  // However, this particular information is being added in codegen,
15269  // because there is an opt-out switch for it (-fno-assume-sane-operator-new)
15270 
15271  // C++2a [basic.stc.dynamic.allocation]p2:
15272  // An allocation function attempts to allocate the requested amount of
15273  // storage. If it is successful, it returns the address of the start of a
15274  // block of storage whose length in bytes is at least as large as the
15275  // requested size.
15276  if (!FD->hasAttr<AllocSizeAttr>()) {
15277  FD->addAttr(AllocSizeAttr::CreateImplicit(
15278  Context, /*ElemSizeParam=*/ParamIdx(1, FD),
15279  /*NumElemsParam=*/ParamIdx(), FD->getLocation()));
15280  }
15281 
15282  // C++2a [basic.stc.dynamic.allocation]p3:
15283  // For an allocation function [...], the pointer returned on a successful
15284  // call shall represent the address of storage that is aligned as follows:
15285  // (3.1) If the allocation function takes an argument of type
15286  // std​::​align_­val_­t, the storage will have the alignment
15287  // specified by the value of this argument.
15288  if (AlignmentParam.hasValue() && !FD->hasAttr<AllocAlignAttr>()) {
15289  FD->addAttr(AllocAlignAttr::CreateImplicit(
15290  Context, ParamIdx(AlignmentParam.getValue(), FD), FD->getLocation()));
15291  }
15292 
15293  // FIXME:
15294  // C++2a [basic.stc.dynamic.allocation]p3:
15295  // For an allocation function [...], the pointer returned on a successful
15296  // call shall represent the address of storage that is aligned as follows:
15297  // (3.2) Otherwise, if the allocation function is named operator new[],
15298  // the storage is aligned for any object that does not have
15299  // new-extended alignment ([basic.align]) and is no larger than the
15300  // requested size.
15301  // (3.3) Otherwise, the storage is aligned for any object that does not
15302  // have new-extended alignment and is of the requested size.
15303 }
15304 
15305 /// Adds any function attributes that we know a priori based on
15306 /// the declaration of this function.
15307 ///
15308 /// These attributes can apply both to implicitly-declared builtins
15309 /// (like __builtin___printf_chk) or to library-declared functions
15310 /// like NSLog or printf.
15311 ///
15312 /// We need to check for duplicate attributes both here and where user-written
15313 /// attributes are applied to declarations.
15315  if (FD->isInvalidDecl())
15316  return;
15317 
15318  // If this is a built-in function, map its builtin attributes to
15319  // actual attributes.
15320  if (unsigned BuiltinID = FD->getBuiltinID()) {
15321  // Handle printf-formatting attributes.
15322  unsigned FormatIdx;
15323  bool HasVAListArg;
15324  if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
15325  if (!FD->hasAttr<FormatAttr>()) {
15326  const char *fmt = "printf";
15327  unsigned int NumParams = FD->getNumParams();
15328  if (FormatIdx < NumParams && // NumParams may be 0 (e.g. vfprintf)
15329  FD->getParamDecl(FormatIdx)->getType()->isObjCObjectPointerType())
15330  fmt = "NSString";
15331  FD->addAttr(FormatAttr::CreateImplicit(Context,
15332  &Context.Idents.get(fmt),
15333  FormatIdx+1,
15334  HasVAListArg ? 0 : FormatIdx+2,
15335  FD->getLocation()));
15336  }
15337  }
15338  if (Context.BuiltinInfo.isScanfLike(BuiltinID, FormatIdx,
15339  HasVAListArg)) {
15340  if (!FD->hasAttr<FormatAttr>())
15341  FD->addAttr(FormatAttr::CreateImplicit(Context,
15342  &Context.Idents.get("scanf"),
15343  FormatIdx+1,
15344  HasVAListArg ? 0 : FormatIdx+2,
15345  FD->getLocation()));
15346  }
15347 
15348  // Handle automatically recognized callbacks.
15350  if (!FD->hasAttr<CallbackAttr>() &&
15351  Context.BuiltinInfo.performsCallback(BuiltinID, Encoding))
15352  FD->addAttr(CallbackAttr::CreateImplicit(
15353  Context, Encoding.data(), Encoding.size(), FD->getLocation()));
15354 
15355  // Mark const if we don't care about errno and that is the only thing
15356  // preventing the function from being const. This allows IRgen to use LLVM
15357  // intrinsics for such functions.
15358  if (!getLangOpts().MathErrno && !FD->hasAttr<ConstAttr>() &&
15359  Context.BuiltinInfo.isConstWithoutErrno(BuiltinID))
15360  FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15361 
15362  // We make "fma" on GNU or Windows const because we know it does not set
15363  // errno in those environments even though it could set errno based on the
15364  // C standard.
15365  const llvm::Triple &Trip = Context.getTargetInfo().getTriple();
15366  if ((Trip.isGNUEnvironment() || Trip.isOSMSVCRT()) &&
15367  !FD->hasAttr<ConstAttr>()) {
15368  switch (BuiltinID) {
15369  case Builtin::BI__builtin_fma:
15370  case Builtin::BI__builtin_fmaf:
15371  case Builtin::BI__builtin_fmal:
15372  case Builtin::BIfma:
15373  case Builtin::BIfmaf:
15374  case Builtin::BIfmal:
15375  FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15376  break;
15377  default:
15378  break;
15379  }
15380  }
15381 
15382  if (Context.BuiltinInfo.isReturnsTwice(BuiltinID) &&
15383  !FD->hasAttr<ReturnsTwiceAttr>())
15384  FD->addAttr(ReturnsTwiceAttr::CreateImplicit(Context,
15385  FD->getLocation()));
15386  if (Context.BuiltinInfo.isNoThrow(BuiltinID) && !FD->hasAttr<NoThrowAttr>())
15387  FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15388  if (Context.BuiltinInfo.isPure(BuiltinID) && !FD->hasAttr<PureAttr>())
15389  FD->addAttr(PureAttr::CreateImplicit(Context, FD->getLocation()));
15390  if (Context.BuiltinInfo.isConst(BuiltinID) && !FD->hasAttr<ConstAttr>())
15391  FD->addAttr(ConstAttr::CreateImplicit(Context, FD->getLocation()));
15392  if (getLangOpts().CUDA && Context.BuiltinInfo.isTSBuiltin(BuiltinID) &&
15393  !FD->hasAttr<CUDADeviceAttr>() && !FD->hasAttr<CUDAHostAttr>()) {
15394  // Add the appropriate attribute, depending on the CUDA compilation mode
15395  // and which target the builtin belongs to. For example, during host
15396  // compilation, aux builtins are __device__, while the rest are __host__.
15397  if (getLangOpts().CUDAIsDevice !=
15398  Context.BuiltinInfo.isAuxBuiltinID(BuiltinID))
15399  FD->addAttr(CUDADeviceAttr::CreateImplicit(Context, FD->getLocation()));
15400  else
15401  FD->addAttr(CUDAHostAttr::CreateImplicit(Context, FD->getLocation()));
15402  }
15403 
15404  // Add known guaranteed alignment for allocation functions.
15405  switch (BuiltinID) {
15406  case Builtin::BImemalign:
15407  case Builtin::BIaligned_alloc:
15408  if (!FD->hasAttr<AllocAlignAttr>())
15409  FD->addAttr(AllocAlignAttr::CreateImplicit(Context, ParamIdx(1, FD),
15410  FD->getLocation()));
15411  break;
15412  default:
15413  break;
15414  }
15415 
15416  // Add allocsize attribute for allocation functions.
15417  switch (BuiltinID) {
15418  case Builtin::BIcalloc:
15419  FD->addAttr(AllocSizeAttr::CreateImplicit(
15420  Context, ParamIdx(1, FD), ParamIdx(2, FD), FD->getLocation()));
15421  break;
15422  case Builtin::BImemalign:
15423  case Builtin::BIaligned_alloc:
15424  case Builtin::BIrealloc:
15425  FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(2, FD),
15426  ParamIdx(), FD->getLocation()));
15427  break;
15428  case Builtin::BImalloc:
15429  FD->addAttr(AllocSizeAttr::CreateImplicit(Context, ParamIdx(1, FD),
15430  ParamIdx(), FD->getLocation()));
15431  break;
15432  default:
15433  break;
15434  }
15435  }
15436 
15437  AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FD);
15438 
15439  // If C++ exceptions are enabled but we are told extern "C" functions cannot
15440  // throw, add an implicit nothrow attribute to any extern "C" function we come
15441  // across.
15442  if (getLangOpts().CXXExceptions && getLangOpts().ExternCNoUnwind &&
15443  FD->isExternC() && !FD->hasAttr<NoThrowAttr>()) {
15444  const auto *FPT = FD->getType()->getAs<FunctionProtoType>();
15445  if (!FPT || FPT->getExceptionSpecType() == EST_None)
15446  FD->addAttr(NoThrowAttr::CreateImplicit(Context, FD->getLocation()));
15447  }
15448 
15449  IdentifierInfo *Name = FD->getIdentifier();
15450  if (!Name)
15451  return;
15452  if ((!getLangOpts().CPlusPlus &&
15453  FD->getDeclContext()->isTranslationUnit()) ||
15454  (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
15455  cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
15457  // Okay: this could be a libc/libm/Objective-C function we know
15458  // about.
15459  } else
15460  return;
15461 
15462  if (Name->isStr("asprintf") || Name->isStr("vasprintf")) {
15463  // FIXME: asprintf and vasprintf aren't C99 functions. Should they be
15464  // target-specific builtins, perhaps?
15465  if (!FD->hasAttr<FormatAttr>())
15466  FD->addAttr(FormatAttr::CreateImplicit(Context,
15467  &Context.Idents.get("printf"), 2,
15468  Name->isStr("vasprintf") ? 0 : 3,
15469  FD->getLocation()));
15470  }
15471 
15472  if (Name->isStr("__CFStringMakeConstantString")) {
15473  // We already have a __builtin___CFStringMakeConstantString,
15474  // but builds that use -fno-constant-cfstrings don't go through that.
15475  if (!FD->hasAttr<FormatArgAttr>())
15476  FD->addAttr(FormatArgAttr::CreateImplicit(Context, ParamIdx(1, FD),
15477  FD->getLocation()));
15478  }
15479 }
15480 
15482  TypeSourceInfo *TInfo) {
15483  assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
15484  assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
15485 
15486  if (!TInfo) {
15487  assert(D.isInvalidType() && "no declarator info for valid type");
15488  TInfo = Context.getTrivialTypeSourceInfo(T);
15489  }
15490 
15491  // Scope manipulation handled by caller.
15492  TypedefDecl *NewTD =
15493  TypedefDecl::Create(Context, CurContext, D.getBeginLoc(),
15494  D.getIdentifierLoc(), D.getIdentifier(), TInfo);
15495 
15496  // Bail out immediately if we have an invalid declaration.
15497  if (D.isInvalidType()) {
15498  NewTD->setInvalidDecl();
15499  return NewTD;
15500  }
15501 
15503  if (CurContext->isFunctionOrMethod())
15504  Diag(NewTD->getLocation(), diag::err_module_private_local)
15505  << 2 << NewTD
15509  else
15510  NewTD->setModulePrivate();
15511  }
15512 
15513  // C++ [dcl.typedef]p8:
15514  // If the typedef declaration defines an unnamed class (or
15515  // enum), the first typedef-name declared by the declaration
15516  // to be that class type (or enum type) is used to denote the
15517  // class type (or enum type) for linkage purposes only.
15518  // We need to check whether the type was declared in the declaration.
15519  switch (D.getDeclSpec().getTypeSpecType()) {
15520  case TST_enum:
15521  case TST_struct:
15522  case TST_interface:
15523  case TST_union:
15524  case TST_class: {
15525  TagDecl *tagFromDeclSpec = cast<TagDecl>(D.getDeclSpec().getRepAsDecl());
15526  setTagNameForLinkagePurposes(tagFromDeclSpec, NewTD);
15527  break;
15528  }
15529 
15530  default:
15531  break;
15532  }
15533 
15534  return NewTD;
15535 }
15536 
15537 /// Check that this is a valid underlying type for an enum declaration.
15539  SourceLocation UnderlyingLoc = TI->getTypeLoc().getBeginLoc();
15540  QualType T = TI->getType();
15541 
15542  if (T->isDependentType())
15543  return false;
15544 
15545  // This doesn't use 'isIntegralType' despite the error message mentioning
15546  // integral type because isIntegralType would also allow enum types in C.
15547  if (const BuiltinType *BT = T->getAs<BuiltinType>())
15548  if (BT->isInteger())
15549  return false;
15550 
15551  if (T->isBitIntType())
15552  return false;
15553 
15554  return Diag(UnderlyingLoc, diag::err_enum_invalid_underlying) << T;
15555 }
15556 
15557 /// Check whether this is a valid redeclaration of a previous enumeration.
15558 /// \return true if the redeclaration was invalid.
15559 bool Sema::CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped,
15560  QualType EnumUnderlyingTy, bool IsFixed,
15561  const EnumDecl *Prev) {
15562  if (IsScoped != Prev->isScoped()) {
15563  Diag(EnumLoc, diag::err_enum_redeclare_scoped_mismatch)
15564  << Prev->isScoped();
15565  Diag(Prev->getLocation(), diag::note_previous_declaration);
15566  return true;
15567  }
15568 
15569  if (IsFixed && Prev->isFixed()) {
15570  if (!EnumUnderlyingTy->isDependentType() &&
15571  !Prev->getIntegerType()->isDependentType() &&
15572  !Context.hasSameUnqualifiedType(EnumUnderlyingTy,
15573  Prev->getIntegerType())) {
15574  // TODO: Highlight the underlying type of the redeclaration.
15575  Diag(EnumLoc, diag::err_enum_redeclare_type_mismatch)
15576  << EnumUnderlyingTy << Prev->getIntegerType();
15577  Diag(Prev->getLocation(), diag::note_previous_declaration)
15578  << Prev->getIntegerTypeRange();
15579  return true;
15580  }
15581  } else if (IsFixed != Prev->isFixed()) {
15582  Diag(EnumLoc, diag::err_enum_redeclare_fixed_mismatch)
15583  << Prev->isFixed();
15584  Diag(Prev->getLocation(), diag::note_previous_declaration);
15585  return true;
15586  }
15587 
15588  return false;
15589 }
15590 
15591 /// Get diagnostic %select index for tag kind for
15592 /// redeclaration diagnostic message.
15593 /// WARNING: Indexes apply to particular diagnostics only!
15594 ///
15595 /// \returns diagnostic %select index.
15597  switch (Tag) {
15598  case TTK_Struct: return 0;
15599  case TTK_Interface: return 1;
15600  case TTK_Class: return 2;
15601  default: llvm_unreachable("Invalid tag kind for redecl diagnostic!");
15602  }
15603 }
15604 
15605 /// Determine if tag kind is a class-key compatible with
15606 /// class for redeclaration (class, struct, or __interface).
15607 ///
15608 /// \returns true iff the tag kind is compatible.
15610 {
15611  return Tag == TTK_Struct || Tag == TTK_Class || Tag == TTK_Interface;
15612 }
15613 
15615  TagTypeKind TTK) {
15616  if (isa<TypedefDecl>(PrevDecl))
15617  return NTK_Typedef;
15618  else if (isa<TypeAliasDecl>(PrevDecl))
15619  return NTK_TypeAlias;
15620  else if (isa<ClassTemplateDecl>(PrevDecl))
15621  return NTK_Template;
15622  else if (isa<TypeAliasTemplateDecl>(PrevDecl))
15623  return NTK_TypeAliasTemplate;
15624  else if (isa<TemplateTemplateParmDecl>(PrevDecl))
15625  return NTK_TemplateTemplateArgument;
15626  switch (TTK) {
15627  case TTK_Struct:
15628  case TTK_Interface:
15629  case TTK_Class:
15630  return getLangOpts().CPlusPlus ? NTK_NonClass : NTK_NonStruct;
15631  case TTK_Union:
15632  return NTK_NonUnion;
15633  case TTK_Enum:
15634  return NTK_NonEnum;
15635  }
15636  llvm_unreachable("invalid TTK");
15637 }
15638 
15639 /// Determine whether a tag with a given kind is acceptable
15640 /// as a redeclaration of the given tag declaration.
15641 ///
15642 /// \returns true if the new tag kind is acceptable, false otherwise.
15644  TagTypeKind NewTag, bool isDefinition,
15645  SourceLocation NewTagLoc,
15646  const IdentifierInfo *Name) {
15647  // C++ [dcl.type.elab]p3:
15648  // The class-key or enum keyword present in the
15649  // elaborated-type-specifier shall agree in kind with the
15650  // declaration to which the name in the elaborated-type-specifier
15651  // refers. This rule also applies to the form of
15652  // elaborated-type-specifier that declares a class-name or
15653  // friend class since it can be construed as referring to the
15654  // definition of the class. Thus, in any
15655  // elaborated-type-specifier, the enum keyword shall be used to
15656  // refer to an enumeration (7.2), the union class-key shall be
15657  // used to refer to a union (clause 9), and either the class or
15658  // struct class-key shall be used to refer to a class (clause 9)
15659  // declared using the class or struct class-key.
15660  TagTypeKind OldTag = Previous->getTagKind();
15661  if (OldTag != NewTag &&
15662  !(isClassCompatTagKind(OldTag) && isClassCompatTagKind(NewTag)))
15663  return false;
15664 
15665  // Tags are compatible, but we might still want to warn on mismatched tags.
15666  // Non-class tags can't be mismatched at this point.
15667  if (!isClassCompatTagKind(NewTag))
15668  return true;
15669 
15670  // Declarations for which -Wmismatched-tags is disabled are entirely ignored
15671  // by our warning analysis. We don't want to warn about mismatches with (eg)
15672  // declarations in system headers that are designed to be specialized, but if
15673  // a user asks us to warn, we should warn if their code contains mismatched
15674  // declarations.
15675  auto IsIgnoredLoc = [&](SourceLocation Loc) {
15676  return getDiagnostics().isIgnored(diag::warn_struct_class_tag_mismatch,
15677  Loc);
15678  };
15679  if (IsIgnoredLoc(NewTagLoc))
15680  return true;
15681 
15682  auto IsIgnored = [&](const TagDecl *Tag) {
15683  return IsIgnoredLoc(Tag->getLocation());
15684  };
15685  while (IsIgnored(Previous)) {
15686  Previous = Previous->getPreviousDecl();
15687  if (!Previous)
15688  return true;
15689  OldTag = Previous->getTagKind();
15690  }
15691 
15692  bool isTemplate = false;
15693  if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Previous))
15694  isTemplate = Record->getDescribedClassTemplate();
15695 
15696  if (inTemplateInstantiation()) {
15697  if (OldTag != NewTag) {
15698  // In a template instantiation, do not offer fix-its for tag mismatches
15699  // since they usually mess up the template instead of fixing the problem.
15700  Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15701  << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15702  << getRedeclDiagFromTagKind(OldTag);
15703  // FIXME: Note previous location?
15704  }
15705  return true;
15706  }
15707 
15708  if (isDefinition) {
15709  // On definitions, check all previous tags and issue a fix-it for each
15710  // one that doesn't match the current tag.
15711  if (Previous->getDefinition()) {
15712  // Don't suggest fix-its for redefinitions.
15713  return true;
15714  }
15715 
15716  bool previousMismatch = false;
15717  for (const TagDecl *I : Previous->redecls()) {
15718  if (I->getTagKind() != NewTag) {
15719  // Ignore previous declarations for which the warning was disabled.
15720  if (IsIgnored(I))
15721  continue;
15722 
15723  if (!previousMismatch) {
15724  previousMismatch = true;
15725  Diag(NewTagLoc, diag::warn_struct_class_previous_tag_mismatch)
15726  << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15727  << getRedeclDiagFromTagKind(I->getTagKind());
15728  }
15729  Diag(I->getInnerLocStart(), diag::note_struct_class_suggestion)
15730  << getRedeclDiagFromTagKind(NewTag)
15731  << FixItHint::CreateReplacement(I->getInnerLocStart(),
15733  }
15734  }
15735  return true;
15736  }
15737 
15738  // Identify the prevailing tag kind: this is the kind of the definition (if
15739  // there is a non-ignored definition), or otherwise the kind of the prior
15740  // (non-ignored) declaration.
15741  const TagDecl *PrevDef = Previous->getDefinition();
15742  if (PrevDef && IsIgnored(PrevDef))
15743  PrevDef = nullptr;
15744  const TagDecl *Redecl = PrevDef ? PrevDef : Previous;
15745  if (Redecl->getTagKind() != NewTag) {
15746  Diag(NewTagLoc, diag::warn_struct_class_tag_mismatch)
15747  << getRedeclDiagFromTagKind(NewTag) << isTemplate << Name
15748  << getRedeclDiagFromTagKind(OldTag);
15749  Diag(Redecl->getLocation(), diag::note_previous_use);
15750 
15751  // If there is a previous definition, suggest a fix-it.
15752  if (PrevDef) {
15753  Diag(NewTagLoc, diag::note_struct_class_suggestion)
15754  << getRedeclDiagFromTagKind(Redecl->getTagKind())
15757  }
15758  }
15759 
15760  return true;
15761 }
15762 
15763 /// Add a minimal nested name specifier fixit hint to allow lookup of a tag name
15764 /// from an outer enclosing namespace or file scope inside a friend declaration.
15765 /// This should provide the commented out code in the following snippet:
15766 /// namespace N {
15767 /// struct X;
15768 /// namespace M {
15769 /// struct Y { friend struct /*N::*/ X; };
15770 /// }
15771 /// }
15773  SourceLocation NameLoc) {
15774  // While the decl is in a namespace, do repeated lookup of that name and see
15775  // if we get the same namespace back. If we do not, continue until
15776  // translation unit scope, at which point we have a fully qualified NNS.
15779  for (; !DC->isTranslationUnit(); DC = DC->getParent()) {
15780  // This tag should be declared in a namespace, which can only be enclosed by
15781  // other namespaces. Bail if there's an anonymous namespace in the chain.
15782  NamespaceDecl *Namespace = dyn_cast<NamespaceDecl>(DC);
15783  if (!Namespace || Namespace->isAnonymousNamespace())
15784  return FixItHint();
15785  IdentifierInfo *II = Namespace->getIdentifier();
15786  Namespaces.push_back(II);
15787  NamedDecl *Lookup = SemaRef.LookupSingleName(
15788  S, II, NameLoc, Sema::LookupNestedNameSpecifierName);
15789  if (Lookup == Namespace)
15790  break;
15791  }
15792 
15793  // Once we have all the namespaces, reverse them to go outermost first, and
15794  // build an NNS.
15795  SmallString<64> Insertion;
15796  llvm::raw_svector_ostream OS(Insertion);
15797  if (DC->isTranslationUnit())
15798  OS << "::";
15799  std::reverse(Namespaces.begin(), Namespaces.end());
15800  for (auto *II : Namespaces)
15801  OS << II->getName() << "::";
15802  return FixItHint::CreateInsertion(NameLoc, Insertion);
15803 }
15804 
15805 /// Determine whether a tag originally declared in context \p OldDC can
15806 /// be redeclared with an unqualified name in \p NewDC (assuming name lookup
15807 /// found a declaration in \p OldDC as a previous decl, perhaps through a
15808 /// using-declaration).
15810  DeclContext *NewDC) {
15811  OldDC = OldDC->getRedeclContext();
15812  NewDC = NewDC->getRedeclContext();
15813 
15814  if (OldDC->Equals(NewDC))
15815  return true;
15816 
15817  // In MSVC mode, we allow a redeclaration if the contexts are related (either
15818  // encloses the other).
15819  if (S.getLangOpts().MSVCCompat &&
15820  (OldDC->Encloses(NewDC) || NewDC->Encloses(OldDC)))
15821  return true;
15822 
15823  return false;
15824 }
15825 
15826 /// This is invoked when we see 'struct foo' or 'struct {'. In the
15827 /// former case, Name will be non-null. In the later case, Name will be null.
15828 /// TagSpec indicates what kind of tag this is. TUK indicates whether this is a
15829 /// reference/declaration/definition of a tag.
15830 ///
15831 /// \param IsTypeSpecifier \c true if this is a type-specifier (or
15832 /// trailing-type-specifier) other than one in an alias-declaration.
15833 ///
15834 /// \param SkipBody If non-null, will be set to indicate if the caller should
15835 /// skip the definition of this tag and treat it as if it were a declaration.
15836 Decl *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK,
15837  SourceLocation KWLoc, CXXScopeSpec &SS,
15838  IdentifierInfo *Name, SourceLocation NameLoc,
15839  const ParsedAttributesView &Attrs, AccessSpecifier AS,
15840  SourceLocation ModulePrivateLoc,
15841  MultiTemplateParamsArg TemplateParameterLists,
15842  bool &OwnedDecl, bool &IsDependent,
15843  SourceLocation ScopedEnumKWLoc,
15844  bool ScopedEnumUsesClassTag, TypeResult UnderlyingType,
15845  bool IsTypeSpecifier, bool IsTemplateParamOrArg,
15846  SkipBodyInfo *SkipBody) {
15847  // If this is not a definition, it must have a name.
15848  IdentifierInfo *OrigName = Name;
15849  assert((Name != nullptr || TUK == TUK_Definition) &&
15850  "Nameless record must be a definition!");
15851  assert(TemplateParameterLists.size() == 0 || TUK != TUK_Reference);
15852 
15853  OwnedDecl = false;
15855  bool ScopedEnum = ScopedEnumKWLoc.isValid();
15856 
15857  // FIXME: Check member specializations more carefully.
15858  bool isMemberSpecialization = false;
15859  bool Invalid = false;
15860 
15861  // We only need to do this matching if we have template parameters
15862  // or a scope specifier, which also conveniently avoids this work
15863  // for non-C++ cases.
15864  if (TemplateParameterLists.size() > 0 ||
15865  (SS.isNotEmpty() && TUK != TUK_Reference)) {
15866  if (TemplateParameterList *TemplateParams =
15867  MatchTemplateParametersToScopeSpecifier(
15868  KWLoc, NameLoc, SS, nullptr, TemplateParameterLists,
15869  TUK == TUK_Friend, isMemberSpecialization, Invalid)) {
15870  if (Kind == TTK_Enum) {
15871  Diag(KWLoc, diag::err_enum_template);
15872  return nullptr;
15873  }
15874 
15875  if (TemplateParams->size() > 0) {
15876  // This is a declaration or definition of a class template (which may
15877  // be a member of another template).
15878 
15879  if (Invalid)
15880  return nullptr;
15881 
15882  OwnedDecl = false;
15883  DeclResult Result = CheckClassTemplate(
15884  S, TagSpec, TUK, KWLoc, SS, Name, NameLoc, Attrs, TemplateParams,
15885  AS, ModulePrivateLoc,
15886  /*FriendLoc*/ SourceLocation(), TemplateParameterLists.size() - 1,
15887  TemplateParameterLists.data(), SkipBody);
15888  return Result.get();
15889  } else {
15890  // The "template<>" header is extraneous.
15891  Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
15893  isMemberSpecialization = true;
15894  }
15895  }
15896 
15897  if (!TemplateParameterLists.empty() && isMemberSpecialization &&
15898  CheckTemplateDeclScope(S, TemplateParameterLists.back()))
15899  return nullptr;
15900  }
15901 
15902  // Figure out the underlying type if this a enum declaration. We need to do
15903  // this early, because it's needed to detect if this is an incompatible
15904  // redeclaration.
15905  llvm::PointerUnion<const Type*, TypeSourceInfo*> EnumUnderlying;
15906  bool IsFixed = !UnderlyingType.isUnset() || ScopedEnum;
15907 
15908  if (Kind == TTK_Enum) {
15909  if (UnderlyingType.isInvalid() || (!UnderlyingType.get() && ScopedEnum)) {
15910  // No underlying type explicitly specified, or we failed to parse the
15911  // type, default to int.
15912  EnumUnderlying = Context.IntTy.getTypePtr();
15913  } else if (UnderlyingType.get()) {
15914  // C++0x 7.2p2: The type-specifier-seq of an enum-base shall name an
15915  // integral type; any cv-qualification is ignored.
15916  TypeSourceInfo *TI = nullptr;
15917  GetTypeFromParser(UnderlyingType.get(), &TI);
15918  EnumUnderlying = TI;
15919 
15920  if (CheckEnumUnderlyingType(TI))
15921  // Recover by falling back to int.
15922  EnumUnderlying = Context.IntTy.getTypePtr();
15923 
15924  if (DiagnoseUnexpandedParameterPack(TI->getTypeLoc().getBeginLoc(), TI,
15925  UPPC_FixedUnderlyingType))
15926  EnumUnderlying = Context.IntTy.getTypePtr();
15927 
15928  } else if (Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment()) {
15929  // For MSVC ABI compatibility, unfixed enums must use an underlying type
15930  // of 'int'. However, if this is an unfixed forward declaration, don't set
15931  // the underlying type unless the user enables -fms-compatibility. This
15932  // makes unfixed forward declared enums incomplete and is more conforming.
15933  if (TUK == TUK_Definition || getLangOpts().MSVCCompat)
15934  EnumUnderlying = Context.IntTy.getTypePtr();
15935  }
15936  }
15937 
15938  DeclContext *SearchDC = CurContext;
15939  DeclContext *DC = CurContext;
15940  bool isStdBadAlloc = false;
15941  bool isStdAlignValT = false;
15942 
15943  RedeclarationKind Redecl = forRedeclarationInCurContext();
15944  if (TUK == TUK_Friend || TUK == TUK_Reference)
15945  Redecl = NotForRedeclaration;
15946 
15947  /// Create a new tag decl in C/ObjC. Since the ODR-like semantics for ObjC/C
15948  /// implemented asks for structural equivalence checking, the returned decl
15949  /// here is passed back to the parser, allowing the tag body to be parsed.
15950  auto createTagFromNewDecl = [&]() -> TagDecl * {
15951  assert(!getLangOpts().CPlusPlus && "not meant for C++ usage");
15952  // If there is an identifier, use the location of the identifier as the
15953  // location of the decl, otherwise use the location of the struct/union
15954  // keyword.
15955  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
15956  TagDecl *New = nullptr;
15957 
15958  if (Kind == TTK_Enum) {
15959  New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name, nullptr,
15960  ScopedEnum, ScopedEnumUsesClassTag, IsFixed);
15961  // If this is an undefined enum, bail.
15962  if (TUK != TUK_Definition && !Invalid)
15963  return nullptr;
15964  if (EnumUnderlying) {
15965  EnumDecl *ED = cast<EnumDecl>(New);
15966  if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo *>())
15967  ED->setIntegerTypeSourceInfo(TI);
15968  else
15969  ED->setIntegerType(QualType(EnumUnderlying.get<const Type *>(), 0));
15970  ED->setPromotionType(ED->getIntegerType());
15971  }
15972  } else { // struct/union
15973  New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
15974  nullptr);
15975  }
15976 
15977  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
15978  // Add alignment attributes if necessary; these attributes are checked
15979  // when the ASTContext lays out the structure.
15980  //
15981  // It is important for implementing the correct semantics that this
15982  // happen here (in ActOnTag). The #pragma pack stack is
15983  // maintained as a result of parser callbacks which can occur at
15984  // many points during the parsing of a struct declaration (because
15985  // the #pragma tokens are effectively skipped over during the
15986  // parsing of the struct).
15987  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
15988  AddAlignmentAttributesForRecord(RD);
15989  AddMsStructLayoutForRecord(RD);
15990  }
15991  }
15992  New->setLexicalDeclContext(CurContext);
15993  return New;
15994  };
15995 
15996  LookupResult Previous(*this, Name, NameLoc, LookupTagName, Redecl);
15997  if (Name && SS.isNotEmpty()) {
15998  // We have a nested-name tag ('struct foo::bar').
15999 
16000  // Check for invalid 'foo::'.
16001  if (SS.isInvalid()) {
16002  Name = nullptr;
16003  goto CreateNewDecl;
16004  }
16005 
16006  // If this is a friend or a reference to a class in a dependent
16007  // context, don't try to make a decl for it.
16008  if (TUK == TUK_Friend || TUK == TUK_Reference) {
16009  DC = computeDeclContext(SS, false);
16010  if (!DC) {
16011  IsDependent = true;
16012  return nullptr;
16013  }
16014  } else {
16015  DC = computeDeclContext(SS, true);
16016  if (!DC) {
16017  Diag(SS.getRange().getBegin(), diag::err_dependent_nested_name_spec)
16018  << SS.getRange();
16019  return nullptr;
16020  }
16021  }
16022 
16023  if (RequireCompleteDeclContext(SS, DC))
16024  return nullptr;
16025 
16026  SearchDC = DC;
16027  // Look-up name inside 'foo::'.
16028  LookupQualifiedName(Previous, DC);
16029 
16030  if (Previous.isAmbiguous())
16031  return nullptr;
16032 
16033  if (Previous.empty()) {
16034  // Name lookup did not find anything. However, if the
16035  // nested-name-specifier refers to the current instantiation,
16036  // and that current instantiation has any dependent base
16037  // classes, we might find something at instantiation time: treat
16038  // this as a dependent elaborated-type-specifier.
16039  // But this only makes any sense for reference-like lookups.
16040  if (Previous.wasNotFoundInCurrentInstantiation() &&
16041  (TUK == TUK_Reference || TUK == TUK_Friend)) {
16042  IsDependent = true;
16043  return nullptr;
16044  }
16045 
16046  // A tag 'foo::bar' must already exist.
16047  Diag(NameLoc, diag::err_not_tag_in_scope)
16048  << Kind << Name << DC << SS.getRange();
16049  Name = nullptr;
16050  Invalid = true;
16051  goto CreateNewDecl;
16052  }
16053  } else if (Name) {
16054  // C++14 [class.mem]p14:
16055  // If T is the name of a class, then each of the following shall have a
16056  // name different from T:
16057  // -- every member of class T that is itself a type
16058  if (TUK != TUK_Reference && TUK != TUK_Friend &&
16059  DiagnoseClassNameShadow(SearchDC, DeclarationNameInfo(Name, NameLoc)))
16060  return nullptr;
16061 
16062  // If this is a named struct, check to see if there was a previous forward
16063  // declaration or definition.
16064  // FIXME: We're looking into outer scopes here, even when we
16065  // shouldn't be. Doing so can result in ambiguities that we
16066  // shouldn't be diagnosing.
16067  LookupName(Previous, S);
16068 
16069  // When declaring or defining a tag, ignore ambiguities introduced
16070  // by types using'ed into this scope.
16071  if (Previous.isAmbiguous() &&
16072  (TUK == TUK_Definition || TUK == TUK_Declaration)) {
16073  LookupResult::Filter F = Previous.makeFilter();
16074  while (F.hasNext()) {
16075  NamedDecl *ND = F.next();
16076  if (!ND->getDeclContext()->getRedeclContext()->Equals(
16077  SearchDC->getRedeclContext()))
16078  F.erase();
16079  }
16080  F.done();
16081  }
16082 
16083  // C++11 [namespace.memdef]p3:
16084  // If the name in a friend declaration is neither qualified nor
16085  // a template-id and the declaration is a function or an
16086  // elaborated-type-specifier, the lookup to determine whether
16087  // the entity has been previously declared shall not consider
16088  // any scopes outside the innermost enclosing namespace.
16089  //
16090  // MSVC doesn't implement the above rule for types, so a friend tag
16091  // declaration may be a redeclaration of a type declared in an enclosing
16092  // scope. They do implement this rule for friend functions.
16093  //
16094  // Does it matter that this should be by scope instead of by
16095  // semantic context?
16096  if (!Previous.empty() && TUK == TUK_Friend) {
16097  DeclContext *EnclosingNS = SearchDC->getEnclosingNamespaceContext();
16098  LookupResult::Filter F = Previous.makeFilter();
16099  bool FriendSawTagOutsideEnclosingNamespace = false;
16100  while (F.hasNext()) {
16101  NamedDecl *ND = F.next();
16103  if (DC->isFileContext() &&
16104  !EnclosingNS->Encloses(ND->getDeclContext())) {
16105  if (getLangOpts().MSVCCompat)
16106  FriendSawTagOutsideEnclosingNamespace = true;
16107  else
16108  F.erase();
16109  }
16110  }
16111  F.done();
16112 
16113  // Diagnose this MSVC extension in the easy case where lookup would have
16114  // unambiguously found something outside the enclosing namespace.
16115  if (Previous.isSingleResult() && FriendSawTagOutsideEnclosingNamespace) {
16116  NamedDecl *ND = Previous.getFoundDecl();
16117  Diag(NameLoc, diag::ext_friend_tag_redecl_outside_namespace)
16118  << createFriendTagNNSFixIt(*this, ND, S, NameLoc);
16119  }
16120  }
16121 
16122  // Note: there used to be some attempt at recovery here.
16123  if (Previous.isAmbiguous())
16124  return nullptr;
16125 
16126  if (!getLangOpts().CPlusPlus && TUK != TUK_Reference) {
16127  // FIXME: This makes sure that we ignore the contexts associated
16128  // with C structs, unions, and enums when looking for a matching
16129  // tag declaration or definition. See the similar lookup tweak
16130  // in Sema::LookupName; is there a better way to deal with this?
16131  while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
16132  SearchDC = SearchDC->getParent();
16133  }
16134  }
16135 
16136  if (Previous.isSingleResult() &&
16137  Previous.getFoundDecl()->isTemplateParameter()) {
16138  // Maybe we will complain about the shadowed template parameter.
16139  DiagnoseTemplateParameterShadow(NameLoc, Previous.getFoundDecl());
16140  // Just pretend that we didn't see the previous declaration.
16141  Previous.clear();
16142  }
16143 
16144  if (getLangOpts().CPlusPlus && Name && DC && StdNamespace &&
16145  DC->Equals(getStdNamespace())) {
16146  if (Name->isStr("bad_alloc")) {
16147  // This is a declaration of or a reference to "std::bad_alloc".
16148  isStdBadAlloc = true;
16149 
16150  // If std::bad_alloc has been implicitly declared (but made invisible to
16151  // name lookup), fill in this implicit declaration as the previous
16152  // declaration, so that the declarations get chained appropriately.
16153  if (Previous.empty() && StdBadAlloc)
16154  Previous.addDecl(getStdBadAlloc());
16155  } else if (Name->isStr("align_val_t")) {
16156  isStdAlignValT = true;
16157  if (Previous.empty() && StdAlignValT)
16158  Previous.addDecl(getStdAlignValT());
16159  }
16160  }
16161 
16162  // If we didn't find a previous declaration, and this is a reference
16163  // (or friend reference), move to the correct scope. In C++, we
16164  // also need to do a redeclaration lookup there, just in case
16165  // there's a shadow friend decl.
16166  if (Name && Previous.empty() &&
16167  (TUK == TUK_Reference || TUK == TUK_Friend || IsTemplateParamOrArg)) {
16168  if (Invalid) goto CreateNewDecl;
16169  assert(SS.isEmpty());
16170 
16171  if (TUK == TUK_Reference || IsTemplateParamOrArg) {
16172  // C++ [basic.scope.pdecl]p5:
16173  // -- for an elaborated-type-specifier of the form
16174  //
16175  // class-key identifier
16176  //
16177  // if the elaborated-type-specifier is used in the
16178  // decl-specifier-seq or parameter-declaration-clause of a
16179  // function defined in namespace scope, the identifier is
16180  // declared as a class-name in the namespace that contains
16181  // the declaration; otherwise, except as a friend
16182  // declaration, the identifier is declared in the smallest
16183  // non-class, non-function-prototype scope that contains the
16184  // declaration.
16185  //
16186  // C99 6.7.2.3p8 has a similar (but not identical!) provision for
16187  // C structs and unions.
16188  //
16189  // It is an error in C++ to declare (rather than define) an enum
16190  // type, including via an elaborated type specifier. We'll
16191  // diagnose that later; for now, declare the enum in the same
16192  // scope as we would have picked for any other tag type.
16193  //
16194  // GNU C also supports this behavior as part of its incomplete
16195  // enum types extension, while GNU C++ does not.
16196  //
16197  // Find the context where we'll be declaring the tag.
16198  // FIXME: We would like to maintain the current DeclContext as the
16199  // lexical context,
16200  SearchDC = getTagInjectionContext(SearchDC);
16201 
16202  // Find the scope where we'll be declaring the tag.
16203  S = getTagInjectionScope(S, getLangOpts());
16204  } else {
16205  assert(TUK == TUK_Friend);
16206  // C++ [namespace.memdef]p3:
16207  // If a friend declaration in a non-local class first declares a
16208  // class or function, the friend class or function is a member of
16209  // the innermost enclosing namespace.
16210  SearchDC = SearchDC->getEnclosingNamespaceContext();
16211  }
16212 
16213  // In C++, we need to do a redeclaration lookup to properly
16214  // diagnose some problems.
16215  // FIXME: redeclaration lookup is also used (with and without C++) to find a
16216  // hidden declaration so that we don't get ambiguity errors when using a
16217  // type declared by an elaborated-type-specifier. In C that is not correct
16218  // and we should instead merge compatible types found by lookup.
16219  if (getLangOpts().CPlusPlus) {
16220  // FIXME: This can perform qualified lookups into function contexts,
16221  // which are meaningless.
16222  Previous.setRedeclarationKind(forRedeclarationInCurContext());
16223  LookupQualifiedName(Previous, SearchDC);
16224  } else {
16225  Previous.setRedeclarationKind(forRedeclarationInCurContext());
16226  LookupName(Previous, S);
16227  }
16228  }
16229 
16230  // If we have a known previous declaration to use, then use it.
16231  if (Previous.empty() && SkipBody && SkipBody->Previous)
16232  Previous.addDecl(SkipBody->Previous);
16233 
16234  if (!Previous.empty()) {
16235  NamedDecl *PrevDecl = Previous.getFoundDecl();
16236  NamedDecl *DirectPrevDecl = Previous.getRepresentativeDecl();
16237 
16238  // It's okay to have a tag decl in the same scope as a typedef
16239  // which hides a tag decl in the same scope. Finding this
16240  // with a redeclaration lookup can only actually happen in C++.
16241  //
16242  // This is also okay for elaborated-type-specifiers, which is
16243  // technically forbidden by the current standard but which is
16244  // okay according to the likely resolution of an open issue;
16245  // see http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#407
16246  if (getLangOpts().CPlusPlus) {
16247  if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16248  if (const TagType *TT = TD->getUnderlyingType()->getAs<TagType>()) {
16249  TagDecl *Tag = TT->getDecl();
16250  if (Tag->getDeclName() == Name &&
16252  ->Equals(TD->getDeclContext()->getRedeclContext())) {
16253  PrevDecl = Tag;
16254  Previous.clear();
16255  Previous.addDecl(Tag);
16256  Previous.resolveKind();
16257  }
16258  }
16259  }
16260  }
16261 
16262  // If this is a redeclaration of a using shadow declaration, it must
16263  // declare a tag in the same context. In MSVC mode, we allow a
16264  // redefinition if either context is within the other.
16265  if (auto *Shadow = dyn_cast<UsingShadowDecl>(DirectPrevDecl)) {
16266  auto *OldTag = dyn_cast<TagDecl>(PrevDecl);
16267  if (SS.isEmpty() && TUK != TUK_Reference && TUK != TUK_Friend &&
16268  isDeclInScope(Shadow, SearchDC, S, isMemberSpecialization) &&
16269  !(OldTag && isAcceptableTagRedeclContext(
16270  *this, OldTag->getDeclContext(), SearchDC))) {
16271  Diag(KWLoc, diag::err_using_decl_conflict_reverse);
16272  Diag(Shadow->getTargetDecl()->getLocation(),
16273  diag::note_using_decl_target);
16274  Diag(Shadow->getIntroducer()->getLocation(), diag::note_using_decl)
16275  << 0;
16276  // Recover by ignoring the old declaration.
16277  Previous.clear();
16278  goto CreateNewDecl;
16279  }
16280  }
16281 
16282  if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
16283  // If this is a use of a previous tag, or if the tag is already declared
16284  // in the same scope (so that the definition/declaration completes or
16285  // rementions the tag), reuse the decl.
16286  if (TUK == TUK_Reference || TUK == TUK_Friend ||
16287  isDeclInScope(DirectPrevDecl, SearchDC, S,
16288  SS.isNotEmpty() || isMemberSpecialization)) {
16289  // Make sure that this wasn't declared as an enum and now used as a
16290  // struct or something similar.
16291  if (!isAcceptableTagRedeclaration(PrevTagDecl, Kind,
16292  TUK == TUK_Definition, KWLoc,
16293  Name)) {
16294  bool SafeToContinue
16295  = (PrevTagDecl->getTagKind() != TTK_Enum &&
16296  Kind != TTK_Enum);
16297  if (SafeToContinue)
16298  Diag(KWLoc, diag::err_use_with_wrong_tag)
16299  << Name
16301  PrevTagDecl->getKindName());
16302  else
16303  Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
16304  Diag(PrevTagDecl->getLocation(), diag::note_previous_use);
16305 
16306  if (SafeToContinue)
16307  Kind = PrevTagDecl->getTagKind();
16308  else {
16309  // Recover by making this an anonymous redefinition.
16310  Name = nullptr;
16311  Previous.clear();
16312  Invalid = true;
16313  }
16314  }
16315 
16316  if (Kind == TTK_Enum && PrevTagDecl->getTagKind() == TTK_Enum) {
16317  const EnumDecl *PrevEnum = cast<EnumDecl>(PrevTagDecl);
16318  if (TUK == TUK_Reference || TUK == TUK_Friend)
16319  return PrevTagDecl;
16320 
16321  QualType EnumUnderlyingTy;
16322  if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16323  EnumUnderlyingTy = TI->getType().getUnqualifiedType();
16324  else if (const Type *T = EnumUnderlying.dyn_cast<const Type*>())
16325  EnumUnderlyingTy = QualType(T, 0);
16326 
16327  // All conflicts with previous declarations are recovered by
16328  // returning the previous declaration, unless this is a definition,
16329  // in which case we want the caller to bail out.
16330  if (CheckEnumRedeclaration(NameLoc.isValid() ? NameLoc : KWLoc,
16331  ScopedEnum, EnumUnderlyingTy,
16332  IsFixed, PrevEnum))
16333  return TUK == TUK_Declaration ? PrevTagDecl : nullptr;
16334  }
16335 
16336  // C++11 [class.mem]p1:
16337  // A member shall not be declared twice in the member-specification,
16338  // except that a nested class or member class template can be declared
16339  // and then later defined.
16340  if (TUK == TUK_Declaration && PrevDecl->isCXXClassMember() &&
16341  S->isDeclScope(PrevDecl)) {
16342  Diag(NameLoc, diag::ext_member_redeclared);
16343  Diag(PrevTagDecl->getLocation(), diag::note_previous_declaration);
16344  }
16345 
16346  if (!Invalid) {
16347  // If this is a use, just return the declaration we found, unless
16348  // we have attributes.
16349  if (TUK == TUK_Reference || TUK == TUK_Friend) {
16350  if (!Attrs.empty()) {
16351  // FIXME: Diagnose these attributes. For now, we create a new
16352  // declaration to hold them.
16353  } else if (TUK == TUK_Reference &&
16354  (PrevTagDecl->getFriendObjectKind() ==
16356  PrevDecl->getOwningModule() != getCurrentModule()) &&
16357  SS.isEmpty()) {
16358  // This declaration is a reference to an existing entity, but
16359  // has different visibility from that entity: it either makes
16360  // a friend visible or it makes a type visible in a new module.
16361  // In either case, create a new declaration. We only do this if
16362  // the declaration would have meant the same thing if no prior
16363  // declaration were found, that is, if it was found in the same
16364  // scope where we would have injected a declaration.
16365  if (!getTagInjectionContext(CurContext)->getRedeclContext()
16366  ->Equals(PrevDecl->getDeclContext()->getRedeclContext()))
16367  return PrevTagDecl;
16368  // This is in the injected scope, create a new declaration in
16369  // that scope.
16370  S = getTagInjectionScope(S, getLangOpts());
16371  } else {
16372  return PrevTagDecl;
16373  }
16374  }
16375 
16376  // Diagnose attempts to redefine a tag.
16377  if (TUK == TUK_Definition) {
16378  if (NamedDecl *Def = PrevTagDecl->getDefinition()) {
16379  // If we're defining a specialization and the previous definition
16380  // is from an implicit instantiation, don't emit an error
16381  // here; we'll catch this in the general case below.
16382  bool IsExplicitSpecializationAfterInstantiation = false;
16383  if (isMemberSpecialization) {
16384  if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Def))
16385  IsExplicitSpecializationAfterInstantiation =
16386  RD->getTemplateSpecializationKind() !=
16388  else if (EnumDecl *ED = dyn_cast<EnumDecl>(Def))
16389  IsExplicitSpecializationAfterInstantiation =
16390  ED->getTemplateSpecializationKind() !=
16392  }
16393 
16394  // Note that clang allows ODR-like semantics for ObjC/C, i.e., do
16395  // not keep more that one definition around (merge them). However,
16396  // ensure the decl passes the structural compatibility check in
16397  // C11 6.2.7/1 (or 6.1.2.6/1 in C89).
16398  NamedDecl *Hidden = nullptr;
16399  if (SkipBody && !hasVisibleDefinition(Def, &Hidden)) {
16400  // There is a definition of this tag, but it is not visible. We
16401  // explicitly make use of C++'s one definition rule here, and
16402  // assume that this definition is identical to the hidden one
16403  // we already have. Make the existing definition visible and
16404  // use it in place of this one.
16405  if (!getLangOpts().CPlusPlus) {
16406  // Postpone making the old definition visible until after we
16407  // complete parsing the new one and do the structural
16408  // comparison.
16409  SkipBody->CheckSameAsPrevious = true;
16410  SkipBody->New = createTagFromNewDecl();
16411  SkipBody->Previous = Def;
16412  return Def;
16413  } else {
16414  SkipBody->ShouldSkip = true;
16415  SkipBody->Previous = Def;
16416  makeMergedDefinitionVisible(Hidden);
16417  // Carry on and handle it like a normal definition. We'll
16418  // skip starting the definitiion later.
16419  }
16420  } else if (!IsExplicitSpecializationAfterInstantiation) {
16421  // A redeclaration in function prototype scope in C isn't
16422  // visible elsewhere, so merely issue a warning.
16423  if (!getLangOpts().CPlusPlus && S->containedInPrototypeScope())
16424  Diag(NameLoc, diag::warn_redefinition_in_param_list) << Name;
16425  else
16426  Diag(NameLoc, diag::err_redefinition) << Name;
16427  notePreviousDefinition(Def,
16428  NameLoc.isValid() ? NameLoc : KWLoc);
16429  // If this is a redefinition, recover by making this
16430  // struct be anonymous, which will make any later
16431  // references get the previous definition.
16432  Name = nullptr;
16433  Previous.clear();
16434  Invalid = true;
16435  }
16436  } else {
16437  // If the type is currently being defined, complain
16438  // about a nested redefinition.
16439  auto *TD = Context.getTagDeclType(PrevTagDecl)->getAsTagDecl();
16440  if (TD->isBeingDefined()) {
16441  Diag(NameLoc, diag::err_nested_redefinition) << Name;
16442  Diag(PrevTagDecl->getLocation(),
16443  diag::note_previous_definition);
16444  Name = nullptr;
16445  Previous.clear();
16446  Invalid = true;
16447  }
16448  }
16449 
16450  // Okay, this is definition of a previously declared or referenced
16451  // tag. We're going to create a new Decl for it.
16452  }
16453 
16454  // Okay, we're going to make a redeclaration. If this is some kind
16455  // of reference, make sure we build the redeclaration in the same DC
16456  // as the original, and ignore the current access specifier.
16457  if (TUK == TUK_Friend || TUK == TUK_Reference) {
16458  SearchDC = PrevTagDecl->getDeclContext();
16459  AS = AS_none;
16460  }
16461  }
16462  // If we get here we have (another) forward declaration or we
16463  // have a definition. Just create a new decl.
16464 
16465  } else {
16466  // If we get here, this is a definition of a new tag type in a nested
16467  // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
16468  // new decl/type. We set PrevDecl to NULL so that the entities
16469  // have distinct types.
16470  Previous.clear();
16471  }
16472  // If we get here, we're going to create a new Decl. If PrevDecl
16473  // is non-NULL, it's a definition of the tag declared by
16474  // PrevDecl. If it's NULL, we have a new definition.
16475 
16476  // Otherwise, PrevDecl is not a tag, but was found with tag
16477  // lookup. This is only actually possible in C++, where a few
16478  // things like templates still live in the tag namespace.
16479  } else {
16480  // Use a better diagnostic if an elaborated-type-specifier
16481  // found the wrong kind of type on the first
16482  // (non-redeclaration) lookup.
16483  if ((TUK == TUK_Reference || TUK == TUK_Friend) &&
16484  !Previous.isForRedeclaration()) {
16485  NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16486  Diag(NameLoc, diag::err_tag_reference_non_tag) << PrevDecl << NTK
16487  << Kind;
16488  Diag(PrevDecl->getLocation(), diag::note_declared_at);
16489  Invalid = true;
16490 
16491  // Otherwise, only diagnose if the declaration is in scope.
16492  } else if (!isDeclInScope(DirectPrevDecl, SearchDC, S,
16493  SS.isNotEmpty() || isMemberSpecialization)) {
16494  // do nothing
16495 
16496  // Diagnose implicit declarations introduced by elaborated types.
16497  } else if (TUK == TUK_Reference || TUK == TUK_Friend) {
16498  NonTagKind NTK = getNonTagTypeDeclKind(PrevDecl, Kind);
16499  Diag(NameLoc, diag::err_tag_reference_conflict) << NTK;
16500  Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16501  Invalid = true;
16502 
16503  // Otherwise it's a declaration. Call out a particularly common
16504  // case here.
16505  } else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(PrevDecl)) {
16506  unsigned Kind = 0;
16507  if (isa<TypeAliasDecl>(PrevDecl)) Kind = 1;
16508  Diag(NameLoc, diag::err_tag_definition_of_typedef)
16509  << Name << Kind << TND->getUnderlyingType();
16510  Diag(PrevDecl->getLocation(), diag::note_previous_decl) << PrevDecl;
16511  Invalid = true;
16512 
16513  // Otherwise, diagnose.
16514  } else {
16515  // The tag name clashes with something else in the target scope,
16516  // issue an error and recover by making this tag be anonymous.
16517  Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
16518  notePreviousDefinition(PrevDecl, NameLoc);
16519  Name = nullptr;
16520  Invalid = true;
16521  }
16522 
16523  // The existing declaration isn't relevant to us; we're in a
16524  // new scope, so clear out the previous declaration.
16525  Previous.clear();
16526  }
16527  }
16528 
16529 CreateNewDecl:
16530 
16531  TagDecl *PrevDecl = nullptr;
16532  if (Previous.isSingleResult())
16533  PrevDecl = cast<TagDecl>(Previous.getFoundDecl());
16534 
16535  // If there is an identifier, use the location of the identifier as the
16536  // location of the decl, otherwise use the location of the struct/union
16537  // keyword.
16538  SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
16539 
16540  // Otherwise, create a new declaration. If there is a previous
16541  // declaration of the same entity, the two will be linked via
16542  // PrevDecl.
16543  TagDecl *New;
16544 
16545  if (Kind == TTK_Enum) {
16546  // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16547  // enum X { A, B, C } D; D should chain to X.
16548  New = EnumDecl::Create(Context, SearchDC, KWLoc, Loc, Name,
16549  cast_or_null<EnumDecl>(PrevDecl), ScopedEnum,
16550  ScopedEnumUsesClassTag, IsFixed);
16551 
16552  if (isStdAlignValT && (!StdAlignValT || getStdAlignValT()->isImplicit()))
16553  StdAlignValT = cast<EnumDecl>(New);
16554 
16555  // If this is an undefined enum, warn.
16556  if (TUK != TUK_Definition && !Invalid) {
16557  TagDecl *Def;
16558  if (IsFixed && cast<EnumDecl>(New)->isFixed()) {
16559  // C++0x: 7.2p2: opaque-enum-declaration.
16560  // Conflicts are diagnosed above. Do nothing.
16561  }
16562  else if (PrevDecl && (Def = cast<EnumDecl>(PrevDecl)->getDefinition())) {
16563  Diag(Loc, diag::ext_forward_ref_enum_def)
16564  << New;
16565  Diag(Def->getLocation(), diag::note_previous_definition);
16566  } else {
16567  unsigned DiagID = diag::ext_forward_ref_enum;
16568  if (getLangOpts().MSVCCompat)
16569  DiagID = diag::ext_ms_forward_ref_enum;
16570  else if (getLangOpts().CPlusPlus)
16571  DiagID = diag::err_forward_ref_enum;
16572  Diag(Loc, DiagID);
16573  }
16574  }
16575 
16576  if (EnumUnderlying) {
16577  EnumDecl *ED = cast<EnumDecl>(New);
16578  if (TypeSourceInfo *TI = EnumUnderlying.dyn_cast<TypeSourceInfo*>())
16579  ED->setIntegerTypeSourceInfo(TI);
16580  else
16581  ED->setIntegerType(QualType(EnumUnderlying.get<const Type*>(), 0));
16582  ED->setPromotionType(ED->getIntegerType());
16583  assert(ED->isComplete() && "enum with type should be complete");
16584  }
16585  } else {
16586  // struct/union/class
16587 
16588  // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
16589  // struct X { int A; } D; D should chain to X.
16590  if (getLangOpts().CPlusPlus) {
16591  // FIXME: Look for a way to use RecordDecl for simple structs.
16592  New = CXXRecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16593  cast_or_null<CXXRecordDecl>(PrevDecl));
16594 
16595  if (isStdBadAlloc && (!StdBadAlloc || getStdBadAlloc()->isImplicit()))
16596  StdBadAlloc = cast<CXXRecordDecl>(New);
16597  } else
16598  New = RecordDecl::Create(Context, Kind, SearchDC, KWLoc, Loc, Name,
16599  cast_or_null<RecordDecl>(PrevDecl));
16600  }
16601 
16602  // C++11 [dcl.type]p3:
16603  // A type-specifier-seq shall not define a class or enumeration [...].
16604  if (getLangOpts().CPlusPlus && (IsTypeSpecifier || IsTemplateParamOrArg) &&
16605  TUK == TUK_Definition) {
16606  Diag(New->getLocation(), diag::err_type_defined_in_type_specifier)
16607  << Context.getTagDeclType(New);
16608  Invalid = true;
16609  }
16610 
16611  if (!Invalid && getLangOpts().CPlusPlus && TUK == TUK_Definition &&
16612  DC->getDeclKind() == Decl::Enum) {
16613  Diag(New->getLocation(), diag::err_type_defined_in_enum)
16614  << Context.getTagDeclType(New);
16615  Invalid = true;
16616  }
16617 
16618  // Maybe add qualifier info.
16619  if (SS.isNotEmpty()) {
16620  if (SS.isSet()) {
16621  // If this is either a declaration or a definition, check the
16622  // nested-name-specifier against the current context.
16623  if ((TUK == TUK_Definition || TUK == TUK_Declaration) &&
16624  diagnoseQualifiedDeclaration(SS, DC, OrigName, Loc,
16625  isMemberSpecialization))
16626  Invalid = true;
16627 
16628  New->setQualifierInfo(SS.getWithLocInContext(Context));
16629  if (TemplateParameterLists.size() > 0) {
16630  New->setTemplateParameterListsInfo(Context, TemplateParameterLists);
16631  }
16632  }
16633  else
16634  Invalid = true;
16635  }
16636 
16637  if (RecordDecl *RD = dyn_cast<RecordDecl>(New)) {
16638  // Add alignment attributes if necessary; these attributes are checked when
16639  // the ASTContext lays out the structure.
16640  //
16641  // It is important for implementing the correct semantics that this
16642  // happen here (in ActOnTag). The #pragma pack stack is
16643  // maintained as a result of parser callbacks which can occur at
16644  // many points during the parsing of a struct declaration (because
16645  // the #pragma tokens are effectively skipped over during the
16646  // parsing of the struct).
16647  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip)) {
16648  AddAlignmentAttributesForRecord(RD);
16649  AddMsStructLayoutForRecord(RD);
16650  }
16651  }
16652 
16653  if (ModulePrivateLoc.isValid()) {
16654  if (isMemberSpecialization)
16655  Diag(New->getLocation(), diag::err_module_private_specialization)
16656  << 2
16657  << FixItHint::CreateRemoval(ModulePrivateLoc);
16658  // __module_private__ does not apply to local classes. However, we only
16659  // diagnose this as an error when the declaration specifiers are
16660  // freestanding. Here, we just ignore the __module_private__.
16661  else if (!SearchDC->isFunctionOrMethod())
16662  New->setModulePrivate();
16663  }
16664 
16665  // If this is a specialization of a member class (of a class template),
16666  // check the specialization.
16667  if (isMemberSpecialization && CheckMemberSpecialization(New, Previous))
16668  Invalid = true;
16669 
16670  // If we're declaring or defining a tag in function prototype scope in C,
16671  // note that this type can only be used within the function and add it to
16672  // the list of decls to inject into the function definition scope.
16673  if ((Name || Kind == TTK_Enum) &&
16674  getNonFieldDeclScope(S)->isFunctionPrototypeScope()) {
16675  if (getLangOpts().CPlusPlus) {
16676  // C++ [dcl.fct]p6:
16677  // Types shall not be defined in return or parameter types.
16678  if (TUK == TUK_Definition && !IsTypeSpecifier) {
16679  Diag(Loc, diag::err_type_defined_in_param_type)
16680  << Name;
16681  Invalid = true;
16682  }
16683  } else if (!PrevDecl) {
16684  Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
16685  }
16686  }
16687 
16688  if (Invalid)
16689  New->setInvalidDecl();
16690 
16691  // Set the lexical context. If the tag has a C++ scope specifier, the
16692  // lexical context will be different from the semantic context.
16693  New->setLexicalDeclContext(CurContext);
16694 
16695  // Mark this as a friend decl if applicable.
16696  // In Microsoft mode, a friend declaration also acts as a forward
16697  // declaration so we always pass true to setObjectOfFriendDecl to make
16698  // the tag name visible.
16699  if (TUK == TUK_Friend)
16700  New->setObjectOfFriendDecl(getLangOpts().MSVCCompat);
16701 
16702  // Set the access specifier.
16703  if (!Invalid && SearchDC->isRecord())
16704  SetMemberAccessSpecifier(New, PrevDecl, AS);
16705 
16706  if (PrevDecl)
16707  CheckRedeclarationInModule(New, PrevDecl);
16708 
16709  if (TUK == TUK_Definition && (!SkipBody || !SkipBody->ShouldSkip))
16710  New->startDefinition();
16711 
16712  ProcessDeclAttributeList(S, New, Attrs);
16713  AddPragmaAttributes(S, New);
16714 
16715  // If this has an identifier, add it to the scope stack.
16716  if (TUK == TUK_Friend) {
16717  // We might be replacing an existing declaration in the lookup tables;
16718  // if so, borrow its access specifier.
16719  if (PrevDecl)
16720  New->setAccess(PrevDecl->getAccess());
16721 
16723  DC->makeDeclVisibleInContext(New);
16724  if (Name) // can be null along some error paths
16725  if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
16726  PushOnScopeChains(New, EnclosingScope, /* AddToContext = */ false);
16727  } else if (Name) {
16728  S = getNonFieldDeclScope(S);
16729  PushOnScopeChains(New, S, true);
16730  } else {
16731  CurContext->addDecl(New);
16732  }
16733 
16734  // If this is the C FILE type, notify the AST context.
16735  if (IdentifierInfo *II = New->getIdentifier())
16736  if (!New->isInvalidDecl() &&
16738  II->isStr("FILE"))
16739  Context.setFILEDecl(New);
16740 
16741  if (PrevDecl)
16742  mergeDeclAttributes(New, PrevDecl);
16743 
16744  if (auto *CXXRD = dyn_cast<CXXRecordDecl>(New))
16745  inferGslOwnerPointerAttribute(CXXRD);
16746 
16747  // If there's a #pragma GCC visibility in scope, set the visibility of this
16748  // record.
16749  AddPushedVisibilityAttribute(New);
16750 
16751  if (isMemberSpecialization && !New->isInvalidDecl())
16752  CompleteMemberSpecialization(New, Previous);
16753 
16754  OwnedDecl = true;
16755  // In C++, don't return an invalid declaration. We can't recover well from
16756  // the cases where we make the type anonymous.
16757  if (Invalid && getLangOpts().CPlusPlus) {
16758  if (New->isBeingDefined())
16759  if (auto RD = dyn_cast<RecordDecl>(New))
16760  RD->completeDefinition();
16761  return nullptr;
16762  } else if (SkipBody && SkipBody->ShouldSkip) {
16763  return SkipBody->Previous;
16764  } else {
16765  return New;
16766  }
16767 }
16768 
16770  AdjustDeclIfTemplate(TagD);
16771  TagDecl *Tag = cast<TagDecl>(TagD);
16772 
16773  // Enter the tag context.
16774  PushDeclContext(S, Tag);
16775 
16776  ActOnDocumentableDecl(TagD);
16777 
16778  // If there's a #pragma GCC visibility in scope, set the visibility of this
16779  // record.
16780  AddPushedVisibilityAttribute(Tag);
16781 }
16782 
16784  SkipBodyInfo &SkipBody) {
16785  if (!hasStructuralCompatLayout(Prev, SkipBody.New))
16786  return false;
16787 
16788  // Make the previous decl visible.
16789  makeMergedDefinitionVisible(SkipBody.Previous);
16790  return true;
16791 }
16792 
16794  assert(isa<ObjCContainerDecl>(IDecl) &&
16795  "ActOnObjCContainerStartDefinition - Not ObjCContainerDecl");
16796  DeclContext *OCD = cast<DeclContext>(IDecl);
16797  assert(OCD->getLexicalParent() == CurContext &&
16798  "The next DeclContext should be lexically contained in the current one.");
16799  CurContext = OCD;
16800  return IDecl;
16801 }
16802 
16804  SourceLocation FinalLoc,
16805  bool IsFinalSpelledSealed,
16806  bool IsAbstract,
16807  SourceLocation LBraceLoc) {
16808  AdjustDeclIfTemplate(TagD);
16809  CXXRecordDecl *Record = cast<CXXRecordDecl>(TagD);
16810 
16811  FieldCollector->StartClass();
16812 
16813  if (!Record->getIdentifier())
16814  return;
16815 
16816  if (IsAbstract)
16817  Record->markAbstract();
16818 
16819  if (FinalLoc.isValid()) {
16820  Record->addAttr(FinalAttr::Create(
16821  Context, FinalLoc, AttributeCommonInfo::AS_Keyword,
16822  static_cast<FinalAttr::Spelling>(IsFinalSpelledSealed)));
16823  }
16824  // C++ [class]p2:
16825  // [...] The class-name is also inserted into the scope of the
16826  // class itself; this is known as the injected-class-name. For
16827  // purposes of access checking, the injected-class-name is treated
16828  // as if it were a public member name.
16829  CXXRecordDecl *InjectedClassName = CXXRecordDecl::Create(
16830  Context, Record->getTagKind(), CurContext, Record->getBeginLoc(),
16831  Record->getLocation(), Record->getIdentifier(),
16832  /*PrevDecl=*/nullptr,
16833  /*DelayTypeCreation=*/true);
16834  Context.getTypeDeclType(InjectedClassName, Record);
16835  InjectedClassName->setImplicit();
16836  InjectedClassName->setAccess(AS_public);
16837  if (ClassTemplateDecl *Template = Record->getDescribedClassTemplate())
16838  InjectedClassName->setDescribedClassTemplate(Template);
16839  PushOnScopeChains(InjectedClassName, S);
16840  assert(InjectedClassName->isInjectedClassName() &&
16841  "Broken injected-class-name");
16842 }
16843 
16845  SourceRange BraceRange) {
16846  AdjustDeclIfTemplate(TagD);
16847  TagDecl *Tag = cast<TagDecl>(TagD);
16848  Tag->setBraceRange(BraceRange);
16849 
16850  // Make sure we "complete" the definition even it is invalid.
16851  if (Tag->isBeingDefined()) {
16852  assert(Tag->isInvalidDecl() && "We should already have completed it");
16853  if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16854  RD->completeDefinition();
16855  }
16856 
16857  if (auto *RD = dyn_cast<CXXRecordDecl>(Tag)) {
16858  FieldCollector->FinishClass();
16859  if (RD->hasAttr<SYCLSpecialClassAttr>() && getLangOpts().SYCLIsDevice) {
16860  auto *Def = RD->getDefinition();
16861  assert(Def && "The record is expected to have a completed definition");
16862  unsigned NumInitMethods = 0;
16863  for (auto *Method : Def->methods()) {
16864  if (!Method->getIdentifier())
16865  continue;
16866  if (Method->getName() == "__init")
16867  NumInitMethods++;
16868  }
16869  if (NumInitMethods > 1 || !Def->hasInitMethod())
16870  Diag(RD->getLocation(), diag::err_sycl_special_type_num_init_method);
16871  }
16872  }
16873 
16874  // Exit this scope of this tag's definition.
16875  PopDeclContext();
16876 
16877  if (getCurLexicalContext()->isObjCContainer() &&
16878  Tag->getDeclContext()->isFileContext())
16880 
16881  // Notify the consumer that we've defined a tag.
16882  if (!Tag->isInvalidDecl())
16883  Consumer.HandleTagDeclDefinition(Tag);
16884 
16885  // Clangs implementation of #pragma align(packed) differs in bitfield layout
16886  // from XLs and instead matches the XL #pragma pack(1) behavior.
16887  if (Context.getTargetInfo().getTriple().isOSAIX() &&
16888  AlignPackStack.hasValue()) {
16889  AlignPackInfo APInfo = AlignPackStack.CurrentValue;
16890  // Only diagnose #pragma align(packed).
16891  if (!APInfo.IsAlignAttr() || APInfo.getAlignMode() != AlignPackInfo::Packed)
16892  return;
16893  const RecordDecl *RD = dyn_cast<RecordDecl>(Tag);
16894  if (!RD)
16895  return;
16896  // Only warn if there is at least 1 bitfield member.
16897  if (llvm::any_of(RD->fields(),
16898  [](const FieldDecl *FD) { return FD->isBitField(); }))
16899  Diag(BraceRange.getBegin(), diag::warn_pragma_align_not_xl_compatible);
16900  }
16901 }
16902 
16904  // Exit this scope of this interface definition.
16905  PopDeclContext();
16906 }
16907 
16909  assert(DC == CurContext && "Mismatch of container contexts");
16910  OriginalLexicalContext = DC;
16911  ActOnObjCContainerFinishDefinition();
16912 }
16913 
16915  ActOnObjCContainerStartDefinition(cast<Decl>(DC));
16916  OriginalLexicalContext = nullptr;
16917 }
16918 
16920  AdjustDeclIfTemplate(TagD);
16921  TagDecl *Tag = cast<TagDecl>(TagD);
16922  Tag->setInvalidDecl();
16923 
16924  // Make sure we "complete" the definition even it is invalid.
16925  if (Tag->isBeingDefined()) {
16926  if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag))
16927  RD->completeDefinition();
16928  }
16929 
16930  // We're undoing ActOnTagStartDefinition here, not
16931  // ActOnStartCXXMemberDeclarations, so we don't have to mess with
16932  // the FieldCollector.
16933 
16934  PopDeclContext();
16935 }
16936 
16937 // Note that FieldName may be null for anonymous bitfields.
16939  IdentifierInfo *FieldName,
16940  QualType FieldTy, bool IsMsStruct,
16941  Expr *BitWidth, bool *ZeroWidth) {
16942  assert(BitWidth);
16943  if (BitWidth->containsErrors())
16944  return ExprError();
16945 
16946  // Default to true; that shouldn't confuse checks for emptiness
16947  if (ZeroWidth)
16948  *ZeroWidth = true;
16949 
16950  // C99 6.7.2.1p4 - verify the field type.
16951  // C++ 9.6p3: A bit-field shall have integral or enumeration type.
16952  if (!FieldTy->isDependentType() && !FieldTy->isIntegralOrEnumerationType()) {
16953  // Handle incomplete and sizeless types with a specific error.
16954  if (RequireCompleteSizedType(FieldLoc, FieldTy,
16955  diag::err_field_incomplete_or_sizeless))
16956  return ExprError();
16957  if (FieldName)
16958  return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
16959  << FieldName << FieldTy << BitWidth->getSourceRange();
16960  return Diag(FieldLoc, diag::err_not_integral_type_anon_bitfield)
16961  << FieldTy << BitWidth->getSourceRange();
16962  } else if (DiagnoseUnexpandedParameterPack(const_cast<Expr *>(BitWidth),
16963  UPPC_BitFieldWidth))
16964  return ExprError();
16965 
16966  // If the bit-width is type- or value-dependent, don't try to check
16967  // it now.
16968  if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
16969  return BitWidth;
16970 
16972  ExprResult ICE = VerifyIntegerConstantExpression(BitWidth, &Value, AllowFold);
16973  if (ICE.isInvalid())
16974  return ICE;
16975  BitWidth = ICE.get();
16976 
16977  if (Value != 0 && ZeroWidth)
16978  *ZeroWidth = false;
16979 
16980  // Zero-width bitfield is ok for anonymous field.
16981  if (Value == 0 && FieldName)
16982  return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
16983 
16984  if (Value.isSigned() && Value.isNegative()) {
16985  if (FieldName)
16986  return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
16987  << FieldName << toString(Value, 10);
16988  return Diag(FieldLoc, diag::err_anon_bitfield_has_negative_width)
16989  << toString(Value, 10);
16990  }
16991 
16992  // The size of the bit-field must not exceed our maximum permitted object
16993  // size.
16994  if (Value.getActiveBits() > ConstantArrayType::getMaxSizeBits(Context)) {
16995  return Diag(FieldLoc, diag::err_bitfield_too_wide)
16996  << !FieldName << FieldName << toString(Value, 10);
16997  }
16998 
16999  if (!FieldTy->isDependentType()) {
17000  uint64_t TypeStorageSize = Context.getTypeSize(FieldTy);
17001  uint64_t TypeWidth = Context.getIntWidth(FieldTy);
17002  bool BitfieldIsOverwide = Value.ugt(TypeWidth);
17003 
17004  // Over-wide bitfields are an error in C or when using the MSVC bitfield
17005  // ABI.
17006  bool CStdConstraintViolation =
17007  BitfieldIsOverwide && !getLangOpts().CPlusPlus;
17008  bool MSBitfieldViolation =
17009  Value.ugt(TypeStorageSize) &&
17010  (IsMsStruct || Context.getTargetInfo().getCXXABI().isMicrosoft());
17011  if (CStdConstraintViolation || MSBitfieldViolation) {
17012  unsigned DiagWidth =
17013  CStdConstraintViolation ? TypeWidth : TypeStorageSize;
17014  return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_width)
17015  << (bool)FieldName << FieldName << toString(Value, 10)
17016  << !CStdConstraintViolation << DiagWidth;
17017  }
17018 
17019  // Warn on types where the user might conceivably expect to get all
17020  // specified bits as value bits: that's all integral types other than
17021  // 'bool'.
17022  if (BitfieldIsOverwide && !FieldTy->isBooleanType() && FieldName) {
17023  Diag(FieldLoc, diag::warn_bitfield_width_exceeds_type_width)
17024  << FieldName << toString(Value, 10)
17025  << (unsigned)TypeWidth;
17026  }
17027  }
17028 
17029  return BitWidth;
17030 }
17031 
17032 /// ActOnField - Each field of a C struct/union is passed into this in order
17033 /// to create a FieldDecl object for it.
17035  Declarator &D, Expr *BitfieldWidth) {
17036  FieldDecl *Res = HandleField(S, cast_or_null<RecordDecl>(TagD),
17037  DeclStart, D, static_cast<Expr*>(BitfieldWidth),
17038  /*InitStyle=*/ICIS_NoInit, AS_public);
17039  return Res;
17040 }
17041 
17042 /// HandleField - Analyze a field of a C struct or a C++ data member.
17043 ///
17045  SourceLocation DeclStart,
17046  Declarator &D, Expr *BitWidth,
17047  InClassInitStyle InitStyle,
17048  AccessSpecifier AS) {
17049  if (D.isDecompositionDeclarator()) {
17051  Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
17052  << Decomp.getSourceRange();
17053  return nullptr;
17054  }
17055 
17056  IdentifierInfo *II = D.getIdentifier();
17057  SourceLocation Loc = DeclStart;
17058  if (II) Loc = D.getIdentifierLoc();
17059 
17060  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17061  QualType T = TInfo->getType();
17062  if (getLangOpts().CPlusPlus) {
17063  CheckExtraCXXDefaultArguments(D);
17064 
17065  if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
17066  UPPC_DataMemberType)) {
17067  D.setInvalidType();
17068  T = Context.IntTy;
17069  TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
17070  }
17071  }
17072 
17073  DiagnoseFunctionSpecifiers(D.getDeclSpec());
17074 
17075  if (D.getDeclSpec().isInlineSpecified())
17076  Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
17077  << getLangOpts().CPlusPlus17;
17080  diag::err_invalid_thread)
17081  << DeclSpec::getSpecifierName(TSCS);
17082 
17083  // Check to see if this name was declared as a member previously
17084  NamedDecl *PrevDecl = nullptr;
17085  LookupResult Previous(*this, II, Loc, LookupMemberName,
17086  ForVisibleRedeclaration);
17087  LookupName(Previous, S);
17088  switch (Previous.getResultKind()) {
17089  case LookupResult::Found:
17091  PrevDecl = Previous.getAsSingle<NamedDecl>();
17092  break;
17093 
17095  PrevDecl = Previous.getRepresentativeDecl();
17096  break;
17097 
17101  break;
17102  }
17103  Previous.suppressDiagnostics();
17104 
17105  if (PrevDecl && PrevDecl->isTemplateParameter()) {
17106  // Maybe we will complain about the shadowed template parameter.
17107  DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
17108  // Just pretend that we didn't see the previous declaration.
17109  PrevDecl = nullptr;
17110  }
17111 
17112  if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
17113  PrevDecl = nullptr;
17114 
17115  bool Mutable
17117  SourceLocation TSSL = D.getBeginLoc();
17118  FieldDecl *NewFD
17119  = CheckFieldDecl(II, T, TInfo, Record, Loc, Mutable, BitWidth, InitStyle,
17120  TSSL, AS, PrevDecl, &D);
17121 
17122  if (NewFD->isInvalidDecl())
17123  Record->setInvalidDecl();
17124 
17126  NewFD->setModulePrivate();
17127 
17128  if (NewFD->isInvalidDecl() && PrevDecl) {
17129  // Don't introduce NewFD into scope; there's already something
17130  // with the same name in the same scope.
17131  } else if (II) {
17132  PushOnScopeChains(NewFD, S);
17133  } else
17134  Record->addDecl(NewFD);
17135 
17136  return NewFD;
17137 }
17138 
17139 /// Build a new FieldDecl and check its well-formedness.
17140 ///
17141 /// This routine builds a new FieldDecl given the fields name, type,
17142 /// record, etc. \p PrevDecl should refer to any previous declaration
17143 /// with the same name and in the same scope as the field to be
17144 /// created.
17145 ///
17146 /// \returns a new FieldDecl.
17147 ///
17148 /// \todo The Declarator argument is a hack. It will be removed once
17150  TypeSourceInfo *TInfo,
17151  RecordDecl *Record, SourceLocation Loc,
17152  bool Mutable, Expr *BitWidth,
17153  InClassInitStyle InitStyle,
17154  SourceLocation TSSL,
17155  AccessSpecifier AS, NamedDecl *PrevDecl,
17156  Declarator *D) {
17157  IdentifierInfo *II = Name.getAsIdentifierInfo();
17158  bool InvalidDecl = false;
17159  if (D) InvalidDecl = D->isInvalidType();
17160 
17161  // If we receive a broken type, recover by assuming 'int' and
17162  // marking this declaration as invalid.
17163  if (T.isNull() || T->containsErrors()) {
17164  InvalidDecl = true;
17165  T = Context.IntTy;
17166  }
17167 
17168  QualType EltTy = Context.getBaseElementType(T);
17169  if (!EltTy->isDependentType() && !EltTy->containsErrors()) {
17170  if (RequireCompleteSizedType(Loc, EltTy,
17171  diag::err_field_incomplete_or_sizeless)) {
17172  // Fields of incomplete type force their record to be invalid.
17173  Record->setInvalidDecl();
17174  InvalidDecl = true;
17175  } else {
17176  NamedDecl *Def;
17177  EltTy->isIncompleteType(&Def);
17178  if (Def && Def->isInvalidDecl()) {
17179  Record->setInvalidDecl();
17180  InvalidDecl = true;
17181  }
17182  }
17183  }
17184 
17185  // TR 18037 does not allow fields to be declared with address space
17186  if (T.hasAddressSpace() || T->isDependentAddressSpaceType() ||
17188  Diag(Loc, diag::err_field_with_address_space);
17189  Record->setInvalidDecl();
17190  InvalidDecl = true;
17191  }
17192 
17193  if (LangOpts.OpenCL) {
17194  // OpenCL v1.2 s6.9b,r & OpenCL v2.0 s6.12.5 - The following types cannot be
17195  // used as structure or union field: image, sampler, event or block types.
17196  if (T->isEventT() || T->isImageType() || T->isSamplerT() ||
17197  T->isBlockPointerType()) {
17198  Diag(Loc, diag::err_opencl_type_struct_or_union_field) << T;
17199  Record->setInvalidDecl();
17200  InvalidDecl = true;
17201  }
17202  // OpenCL v1.2 s6.9.c: bitfields are not supported, unless Clang extension
17203  // is enabled.
17204  if (BitWidth && !getOpenCLOptions().isAvailableOption(
17205  "__cl_clang_bitfields", LangOpts)) {
17206  Diag(Loc, diag::err_opencl_bitfields);
17207  InvalidDecl = true;
17208  }
17209  }
17210 
17211  // Anonymous bit-fields cannot be cv-qualified (CWG 2229).
17212  if (!InvalidDecl && getLangOpts().CPlusPlus && !II && BitWidth &&
17213  T.hasQualifiers()) {
17214  InvalidDecl = true;
17215  Diag(Loc, diag::err_anon_bitfield_qualifiers);
17216  }
17217 
17218  // C99 6.7.2.1p8: A member of a structure or union may have any type other
17219  // than a variably modified type.
17220  if (!InvalidDecl && T->isVariablyModifiedType()) {
17221  if (!tryToFixVariablyModifiedVarType(
17222  TInfo, T, Loc, diag::err_typecheck_field_variable_size))
17223  InvalidDecl = true;
17224  }
17225 
17226  // Fields can not have abstract class types
17227  if (!InvalidDecl && RequireNonAbstractType(Loc, T,
17228  diag::err_abstract_type_in_decl,
17229  AbstractFieldType))
17230  InvalidDecl = true;
17231 
17232  bool ZeroWidth = false;
17233  if (InvalidDecl)
17234  BitWidth = nullptr;
17235  // If this is declared as a bit-field, check the bit-field.
17236  if (BitWidth) {
17237  BitWidth = VerifyBitField(Loc, II, T, Record->isMsStruct(Context), BitWidth,
17238  &ZeroWidth).get();
17239  if (!BitWidth) {
17240  InvalidDecl = true;
17241  BitWidth = nullptr;
17242  ZeroWidth = false;
17243  }
17244  }
17245 
17246  // Check that 'mutable' is consistent with the type of the declaration.
17247  if (!InvalidDecl && Mutable) {
17248  unsigned DiagID = 0;
17249  if (T->isReferenceType())
17250  DiagID = getLangOpts().MSVCCompat ? diag::ext_mutable_reference
17251  : diag::err_mutable_reference;
17252  else if (T.isConstQualified())
17253  DiagID = diag::err_mutable_const;
17254 
17255  if (DiagID) {
17256  SourceLocation ErrLoc = Loc;
17257  if (D && D->getDeclSpec().getStorageClassSpecLoc().isValid())
17258  ErrLoc = D->getDeclSpec().getStorageClassSpecLoc();
17259  Diag(ErrLoc, DiagID);
17260  if (DiagID != diag::ext_mutable_reference) {
17261  Mutable = false;
17262  InvalidDecl = true;
17263  }
17264  }
17265  }
17266 
17267  // C++11 [class.union]p8 (DR1460):
17268  // At most one variant member of a union may have a
17269  // brace-or-equal-initializer.
17270  if (InitStyle != ICIS_NoInit)
17271  checkDuplicateDefaultInit(*this, cast<CXXRecordDecl>(Record), Loc);
17272 
17273  FieldDecl *NewFD = FieldDecl::Create(Context, Record, TSSL, Loc, II, T, TInfo,
17274  BitWidth, Mutable, InitStyle);
17275  if (InvalidDecl)
17276  NewFD->setInvalidDecl();
17277 
17278  if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
17279  Diag(Loc, diag::err_duplicate_member) << II;
17280  Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17281  NewFD->setInvalidDecl();
17282  }
17283 
17284  if (!InvalidDecl && getLangOpts().CPlusPlus) {
17285  if (Record->isUnion()) {
17286  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17287  CXXRecordDecl* RDecl = cast<CXXRecordDecl>(RT->getDecl());
17288  if (RDecl->getDefinition()) {
17289  // C++ [class.union]p1: An object of a class with a non-trivial
17290  // constructor, a non-trivial copy constructor, a non-trivial
17291  // destructor, or a non-trivial copy assignment operator
17292  // cannot be a member of a union, nor can an array of such
17293  // objects.
17294  if (CheckNontrivialField(NewFD))
17295  NewFD->setInvalidDecl();
17296  }
17297  }
17298 
17299  // C++ [class.union]p1: If a union contains a member of reference type,
17300  // the program is ill-formed, except when compiling with MSVC extensions
17301  // enabled.
17302  if (EltTy->isReferenceType()) {
17303  Diag(NewFD->getLocation(), getLangOpts().MicrosoftExt ?
17304  diag::ext_union_member_of_reference_type :
17305  diag::err_union_member_of_reference_type)
17306  << NewFD->getDeclName() << EltTy;
17307  if (!getLangOpts().MicrosoftExt)
17308  NewFD->setInvalidDecl();
17309  }
17310  }
17311  }
17312 
17313  // FIXME: We need to pass in the attributes given an AST
17314  // representation, not a parser representation.
17315  if (D) {
17316  // FIXME: The current scope is almost... but not entirely... correct here.
17317  ProcessDeclAttributes(getCurScope(), NewFD, *D);
17318 
17319  if (NewFD->hasAttrs())
17320  CheckAlignasUnderalignment(NewFD);
17321  }
17322 
17323  // In auto-retain/release, infer strong retension for fields of
17324  // retainable type.
17325  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewFD))
17326  NewFD->setInvalidDecl();
17327 
17328  if (T.isObjCGCWeak())
17329  Diag(Loc, diag::warn_attribute_weak_on_field);
17330 
17331  // PPC MMA non-pointer types are not allowed as field types.
17332  if (Context.getTargetInfo().getTriple().isPPC64() &&
17333  CheckPPCMMAType(T, NewFD->getLocation()))
17334  NewFD->setInvalidDecl();
17335 
17336  NewFD->setAccess(AS);
17337  return NewFD;
17338 }
17339 
17341  assert(FD);
17342  assert(getLangOpts().CPlusPlus && "valid check only for C++");
17343 
17344  if (FD->isInvalidDecl() || FD->getType()->isDependentType())
17345  return false;
17346 
17347  QualType EltTy = Context.getBaseElementType(FD->getType());
17348  if (const RecordType *RT = EltTy->getAs<RecordType>()) {
17349  CXXRecordDecl *RDecl = cast<CXXRecordDecl>(RT->getDecl());
17350  if (RDecl->getDefinition()) {
17351  // We check for copy constructors before constructors
17352  // because otherwise we'll never get complaints about
17353  // copy constructors.
17354 
17355  CXXSpecialMember member = CXXInvalid;
17356  // We're required to check for any non-trivial constructors. Since the
17357  // implicit default constructor is suppressed if there are any
17358  // user-declared constructors, we just need to check that there is a
17359  // trivial default constructor and a trivial copy constructor. (We don't
17360  // worry about move constructors here, since this is a C++98 check.)
17361  if (RDecl->hasNonTrivialCopyConstructor())
17362  member = CXXCopyConstructor;
17363  else if (!RDecl->hasTrivialDefaultConstructor())
17364  member = CXXDefaultConstructor;
17365  else if (RDecl->hasNonTrivialCopyAssignment())
17366  member = CXXCopyAssignment;
17367  else if (RDecl->hasNonTrivialDestructor())
17368  member = CXXDestructor;
17369 
17370  if (member != CXXInvalid) {
17371  if (!getLangOpts().CPlusPlus11 &&
17372  getLangOpts().ObjCAutoRefCount && RDecl->hasObjectMember()) {
17373  // Objective-C++ ARC: it is an error to have a non-trivial field of
17374  // a union. However, system headers in Objective-C programs
17375  // occasionally have Objective-C lifetime objects within unions,
17376  // and rather than cause the program to fail, we make those
17377  // members unavailable.
17378  SourceLocation Loc = FD->getLocation();
17379  if (getSourceManager().isInSystemHeader(Loc)) {
17380  if (!FD->hasAttr<UnavailableAttr>())
17381  FD->addAttr(UnavailableAttr::CreateImplicit(Context, "",
17382  UnavailableAttr::IR_ARCFieldWithOwnership, Loc));
17383  return false;
17384  }
17385  }
17386 
17387  Diag(FD->getLocation(), getLangOpts().CPlusPlus11 ?
17388  diag::warn_cxx98_compat_nontrivial_union_or_anon_struct_member :
17389  diag::err_illegal_union_or_anon_struct_member)
17390  << FD->getParent()->isUnion() << FD->getDeclName() << member;
17391  DiagnoseNontrivial(RDecl, member);
17392  return !getLangOpts().CPlusPlus11;
17393  }
17394  }
17395  }
17396 
17397  return false;
17398 }
17399 
17400 /// TranslateIvarVisibility - Translate visibility from a token ID to an
17401 /// AST enum value.
17404  switch (ivarVisibility) {
17405  default: llvm_unreachable("Unknown visitibility kind");
17406  case tok::objc_private: return ObjCIvarDecl::Private;
17407  case tok::objc_public: return ObjCIvarDecl::Public;
17408  case tok::objc_protected: return ObjCIvarDecl::Protected;
17409  case tok::objc_package: return ObjCIvarDecl::Package;
17410  }
17411 }
17412 
17413 /// ActOnIvar - Each ivar field of an objective-c class is passed into this
17414 /// in order to create an IvarDecl object for it.
17416  SourceLocation DeclStart,
17417  Declarator &D, Expr *BitfieldWidth,
17419 
17420  IdentifierInfo *II = D.getIdentifier();
17421  Expr *BitWidth = (Expr*)BitfieldWidth;
17422  SourceLocation Loc = DeclStart;
17423  if (II) Loc = D.getIdentifierLoc();
17424 
17425  // FIXME: Unnamed fields can be handled in various different ways, for
17426  // example, unnamed unions inject all members into the struct namespace!
17427 
17428  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
17429  QualType T = TInfo->getType();
17430 
17431  if (BitWidth) {
17432  // 6.7.2.1p3, 6.7.2.1p4
17433  BitWidth = VerifyBitField(Loc, II, T, /*IsMsStruct*/false, BitWidth).get();
17434  if (!BitWidth)
17435  D.setInvalidType();
17436  } else {
17437  // Not a bitfield.
17438 
17439  // validate II.
17440 
17441  }
17442  if (T->isReferenceType()) {
17443  Diag(Loc, diag::err_ivar_reference_type);
17444  D.setInvalidType();
17445  }
17446  // C99 6.7.2.1p8: A member of a structure or union may have any type other
17447  // than a variably modified type.
17448  else if (T->isVariablyModifiedType()) {
17449  if (!tryToFixVariablyModifiedVarType(
17450  TInfo, T, Loc, diag::err_typecheck_ivar_variable_size))
17451  D.setInvalidType();
17452  }
17453 
17454  // Get the visibility (access control) for this ivar.
17456  Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
17458  // Must set ivar's DeclContext to its enclosing interface.
17459  ObjCContainerDecl *EnclosingDecl = cast<ObjCContainerDecl>(CurContext);
17460  if (!EnclosingDecl || EnclosingDecl->isInvalidDecl())
17461  return nullptr;
17462  ObjCContainerDecl *EnclosingContext;
17463  if (ObjCImplementationDecl *IMPDecl =
17464  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17465  if (LangOpts.ObjCRuntime.isFragile()) {
17466  // Case of ivar declared in an implementation. Context is that of its class.
17467  EnclosingContext = IMPDecl->getClassInterface();
17468  assert(EnclosingContext && "Implementation has no class interface!");
17469  }
17470  else
17471  EnclosingContext = EnclosingDecl;
17472  } else {
17473  if (ObjCCategoryDecl *CDecl =
17474  dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17475  if (LangOpts.ObjCRuntime.isFragile() || !CDecl->IsClassExtension()) {
17476  Diag(Loc, diag::err_misplaced_ivar) << CDecl->IsClassExtension();
17477  return nullptr;
17478  }
17479  }
17480  EnclosingContext = EnclosingDecl;
17481  }
17482 
17483  // Construct the decl.
17484  ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, EnclosingContext,
17485  DeclStart, Loc, II, T,
17486  TInfo, ac, (Expr *)BitfieldWidth);
17487 
17488  if (II) {
17489  NamedDecl *PrevDecl = LookupSingleName(S, II, Loc, LookupMemberName,
17490  ForVisibleRedeclaration);
17491  if (PrevDecl && isDeclInScope(PrevDecl, EnclosingContext, S)
17492  && !isa<TagDecl>(PrevDecl)) {
17493  Diag(Loc, diag::err_duplicate_member) << II;
17494  Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
17495  NewID->setInvalidDecl();
17496  }
17497  }
17498 
17499  // Process attributes attached to the ivar.
17500  ProcessDeclAttributes(S, NewID, D);
17501 
17502  if (D.isInvalidType())
17503  NewID->setInvalidDecl();
17504 
17505  // In ARC, infer 'retaining' for ivars of retainable type.
17506  if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(NewID))
17507  NewID->setInvalidDecl();
17508 
17510  NewID->setModulePrivate();
17511 
17512  if (II) {
17513  // FIXME: When interfaces are DeclContexts, we'll need to add
17514  // these to the interface.
17515  S->AddDecl(NewID);
17516  IdResolver.AddDecl(NewID);
17517  }
17518 
17519  if (LangOpts.ObjCRuntime.isNonFragile() &&
17520  !NewID->isInvalidDecl() && isa<ObjCInterfaceDecl>(EnclosingDecl))
17521  Diag(Loc, diag::warn_ivars_in_interface);
17522 
17523  return NewID;
17524 }
17525 
17526 /// ActOnLastBitfield - This routine handles synthesized bitfields rules for
17527 /// class and class extensions. For every class \@interface and class
17528 /// extension \@interface, if the last ivar is a bitfield of any type,
17529 /// then add an implicit `char :0` ivar to the end of that interface.
17531  SmallVectorImpl<Decl *> &AllIvarDecls) {
17532  if (LangOpts.ObjCRuntime.isFragile() || AllIvarDecls.empty())
17533  return;
17534 
17535  Decl *ivarDecl = AllIvarDecls[AllIvarDecls.size()-1];
17536  ObjCIvarDecl *Ivar = cast<ObjCIvarDecl>(ivarDecl);
17537 
17538  if (!Ivar->isBitField() || Ivar->isZeroLengthBitField(Context))
17539  return;
17540  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CurContext);
17541  if (!ID) {
17542  if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(CurContext)) {
17543  if (!CD->IsClassExtension())
17544  return;
17545  }
17546  // No need to add this to end of @implementation.
17547  else
17548  return;
17549  }
17550  // All conditions are met. Add a new bitfield to the tail end of ivars.
17551  llvm::APInt Zero(Context.getTypeSize(Context.IntTy), 0);
17552  Expr * BW = IntegerLiteral::Create(Context, Zero, Context.IntTy, DeclLoc);
17553 
17554  Ivar = ObjCIvarDecl::Create(Context, cast<ObjCContainerDecl>(CurContext),
17555  DeclLoc, DeclLoc, nullptr,
17556  Context.CharTy,
17557  Context.getTrivialTypeSourceInfo(Context.CharTy,
17558  DeclLoc),
17560  true);
17561  AllIvarDecls.push_back(Ivar);
17562 }
17563 
17564 void Sema::ActOnFields(Scope *S, SourceLocation RecLoc, Decl *EnclosingDecl,
17565  ArrayRef<Decl *> Fields, SourceLocation LBrac,
17566  SourceLocation RBrac,
17567  const ParsedAttributesView &Attrs) {
17568  assert(EnclosingDecl && "missing record or interface decl");
17569 
17570  // If this is an Objective-C @implementation or category and we have
17571  // new fields here we should reset the layout of the interface since
17572  // it will now change.
17573  if (!Fields.empty() && isa<ObjCContainerDecl>(EnclosingDecl)) {
17574  ObjCContainerDecl *DC = cast<ObjCContainerDecl>(EnclosingDecl);
17575  switch (DC->getKind()) {
17576  default: break;
17577  case Decl::ObjCCategory:
17578  Context.ResetObjCLayout(cast<ObjCCategoryDecl>(DC)->getClassInterface());
17579  break;
17580  case Decl::ObjCImplementation:
17581  Context.
17582  ResetObjCLayout(cast<ObjCImplementationDecl>(DC)->getClassInterface());
17583  break;
17584  }
17585  }
17586 
17587  RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
17588  CXXRecordDecl *CXXRecord = dyn_cast<CXXRecordDecl>(EnclosingDecl);
17589 
17590  // Start counting up the number of named members; make sure to include
17591  // members of anonymous structs and unions in the total.
17592  unsigned NumNamedMembers = 0;
17593  if (Record) {
17594  for (const auto *I : Record->decls()) {
17595  if (const auto *IFD = dyn_cast<IndirectFieldDecl>(I))
17596  if (IFD->getDeclName())
17597  ++NumNamedMembers;
17598  }
17599  }
17600 
17601  // Verify that all the fields are okay.
17602  SmallVector<FieldDecl*, 32> RecFields;
17603 
17604  for (ArrayRef<Decl *>::iterator i = Fields.begin(), end = Fields.end();
17605  i != end; ++i) {
17606  FieldDecl *FD = cast<FieldDecl>(*i);
17607 
17608  // Get the type for the field.
17609  const Type *FDTy = FD->getType().getTypePtr();
17610 
17611  if (!FD->isAnonymousStructOrUnion()) {
17612  // Remember all fields written by the user.
17613  RecFields.push_back(FD);
17614  }
17615 
17616  // If the field is already invalid for some reason, don't emit more
17617  // diagnostics about it.
17618  if (FD->isInvalidDecl()) {
17619  EnclosingDecl->setInvalidDecl();
17620  continue;
17621  }
17622 
17623  // C99 6.7.2.1p2:
17624  // A structure or union shall not contain a member with
17625  // incomplete or function type (hence, a structure shall not
17626  // contain an instance of itself, but may contain a pointer to
17627  // an instance of itself), except that the last member of a
17628  // structure with more than one named member may have incomplete
17629  // array type; such a structure (and any union containing,
17630  // possibly recursively, a member that is such a structure)
17631  // shall not be a member of a structure or an element of an
17632  // array.
17633  bool IsLastField = (i + 1 == Fields.end());
17634  if (FDTy->isFunctionType()) {
17635  // Field declared as a function.
17636  Diag(FD->getLocation(), diag::err_field_declared_as_function)
17637  << FD->getDeclName();
17638  FD->setInvalidDecl();
17639  EnclosingDecl->setInvalidDecl();
17640  continue;
17641  } else if (FDTy->isIncompleteArrayType() &&
17642  (Record || isa<ObjCContainerDecl>(EnclosingDecl))) {
17643  if (Record) {
17644  // Flexible array member.
17645  // Microsoft and g++ is more permissive regarding flexible array.
17646  // It will accept flexible array in union and also
17647  // as the sole element of a struct/class.
17648  unsigned DiagID = 0;
17649  if (!Record->isUnion() && !IsLastField) {
17650  Diag(FD->getLocation(), diag::err_flexible_array_not_at_end)
17651  << FD->getDeclName() << FD->getType() << Record->getTagKind();
17652  Diag((*(i + 1))->getLocation(), diag::note_next_field_declaration);
17653  FD->setInvalidDecl();
17654  EnclosingDecl->setInvalidDecl();
17655  continue;
17656  } else if (Record->isUnion())
17657  DiagID = getLangOpts().MicrosoftExt
17658  ? diag::ext_flexible_array_union_ms
17659  : getLangOpts().CPlusPlus
17660  ? diag::ext_flexible_array_union_gnu
17661  : diag::err_flexible_array_union;
17662  else if (NumNamedMembers < 1)
17663  DiagID = getLangOpts().MicrosoftExt
17664  ? diag::ext_flexible_array_empty_aggregate_ms
17665  : getLangOpts().CPlusPlus
17666  ? diag::ext_flexible_array_empty_aggregate_gnu
17667  : diag::err_flexible_array_empty_aggregate;
17668 
17669  if (DiagID)
17670  Diag(FD->getLocation(), DiagID) << FD->getDeclName()
17671  << Record->getTagKind();
17672  // While the layout of types that contain virtual bases is not specified
17673  // by the C++ standard, both the Itanium and Microsoft C++ ABIs place
17674  // virtual bases after the derived members. This would make a flexible
17675  // array member declared at the end of an object not adjacent to the end
17676  // of the type.
17677  if (CXXRecord && CXXRecord->getNumVBases() != 0)
17678  Diag(FD->getLocation(), diag::err_flexible_array_virtual_base)
17679  << FD->getDeclName() << Record->getTagKind();
17680  if (!getLangOpts().C99)
17681  Diag(FD->getLocation(), diag::ext_c99_flexible_array_member)
17682  << FD->getDeclName() << Record->getTagKind();
17683 
17684  // If the element type has a non-trivial destructor, we would not
17685  // implicitly destroy the elements, so disallow it for now.
17686  //
17687  // FIXME: GCC allows this. We should probably either implicitly delete
17688  // the destructor of the containing class, or just allow this.
17689  QualType BaseElem = Context.getBaseElementType(FD->getType());
17690  if (!BaseElem->isDependentType() && BaseElem.isDestructedType()) {
17691  Diag(FD->getLocation(), diag::err_flexible_array_has_nontrivial_dtor)
17692  << FD->getDeclName() << FD->getType();
17693  FD->setInvalidDecl();
17694  EnclosingDecl->setInvalidDecl();
17695  continue;
17696  }
17697  // Okay, we have a legal flexible array member at the end of the struct.
17698  Record->setHasFlexibleArrayMember(true);
17699  } else {
17700  // In ObjCContainerDecl ivars with incomplete array type are accepted,
17701  // unless they are followed by another ivar. That check is done
17702  // elsewhere, after synthesized ivars are known.
17703  }
17704  } else if (!FDTy->isDependentType() &&
17705  RequireCompleteSizedType(
17706  FD->getLocation(), FD->getType(),
17707  diag::err_field_incomplete_or_sizeless)) {
17708  // Incomplete type
17709  FD->setInvalidDecl();
17710  EnclosingDecl->setInvalidDecl();
17711  continue;
17712  } else if (const RecordType *FDTTy = FDTy->getAs<RecordType>()) {
17713  if (Record && FDTTy->getDecl()->hasFlexibleArrayMember()) {
17714  // A type which contains a flexible array member is considered to be a
17715  // flexible array member.
17716  Record->setHasFlexibleArrayMember(true);
17717  if (!Record->isUnion()) {
17718  // If this is a struct/class and this is not the last element, reject
17719  // it. Note that GCC supports variable sized arrays in the middle of
17720  // structures.
17721  if (!IsLastField)
17722  Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
17723  << FD->getDeclName() << FD->getType();
17724  else {
17725  // We support flexible arrays at the end of structs in
17726  // other structs as an extension.
17727  Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
17728  << FD->getDeclName();
17729  }
17730  }
17731  }
17732  if (isa<ObjCContainerDecl>(EnclosingDecl) &&
17733  RequireNonAbstractType(FD->getLocation(), FD->getType(),
17734  diag::err_abstract_type_in_decl,
17735  AbstractIvarType)) {
17736  // Ivars can not have abstract class types
17737  FD->setInvalidDecl();
17738  }
17739  if (Record && FDTTy->getDecl()->hasObjectMember())
17740  Record->setHasObjectMember(true);
17741  if (Record && FDTTy->getDecl()->hasVolatileMember())
17742  Record->setHasVolatileMember(true);
17743  } else if (FDTy->isObjCObjectType()) {
17744  /// A field cannot be an Objective-c object
17745  Diag(FD->getLocation(), diag::err_statically_allocated_object)
17746  << FixItHint::CreateInsertion(FD->getLocation(), "*");
17747  QualType T = Context.getObjCObjectPointerType(FD->getType());
17748  FD->setType(T);
17749  } else if (Record && Record->isUnion() &&
17751  getSourceManager().isInSystemHeader(FD->getLocation()) &&
17752  !getLangOpts().CPlusPlus && !FD->hasAttr<UnavailableAttr>() &&
17754  !Context.hasDirectOwnershipQualifier(FD->getType()))) {
17755  // For backward compatibility, fields of C unions declared in system
17756  // headers that have non-trivial ObjC ownership qualifications are marked
17757  // as unavailable unless the qualifier is explicit and __strong. This can
17758  // break ABI compatibility between programs compiled with ARC and MRR, but
17759  // is a better option than rejecting programs using those unions under
17760  // ARC.
17761  FD->addAttr(UnavailableAttr::CreateImplicit(
17762  Context, "", UnavailableAttr::IR_ARCFieldWithOwnership,
17763  FD->getLocation()));
17764  } else if (getLangOpts().ObjC &&
17765  getLangOpts().getGC() != LangOptions::NonGC && Record &&
17766  !Record->hasObjectMember()) {
17767  if (FD->getType()->isObjCObjectPointerType() ||
17768  FD->getType().isObjCGCStrong())
17769  Record->setHasObjectMember(true);
17770  else if (Context.getAsArrayType(FD->getType())) {
17771  QualType BaseType = Context.getBaseElementType(FD->getType());
17772  if (BaseType->isRecordType() &&
17773  BaseType->castAs<RecordType>()->getDecl()->hasObjectMember())
17774  Record->setHasObjectMember(true);
17775  else if (BaseType->isObjCObjectPointerType() ||
17776  BaseType.isObjCGCStrong())
17777  Record->setHasObjectMember(true);
17778  }
17779  }
17780 
17781  if (Record && !getLangOpts().CPlusPlus &&
17782  !shouldIgnoreForRecordTriviality(FD)) {
17783  QualType FT = FD->getType();
17787  Record->isUnion())
17789  }
17792  Record->setNonTrivialToPrimitiveCopy(true);
17793  if (FT.hasNonTrivialToPrimitiveCopyCUnion() || Record->isUnion())
17795  }
17796  if (FT.isDestructedType()) {
17797  Record->setNonTrivialToPrimitiveDestroy(true);
17798  Record->setParamDestroyedInCallee(true);
17799  if (FT.hasNonTrivialToPrimitiveDestructCUnion() || Record->isUnion())
17801  }
17802 
17803  if (const auto *RT = FT->getAs<RecordType>()) {
17804  if (RT->getDecl()->getArgPassingRestrictions() ==
17807  } else if (FT.getQualifiers().getObjCLifetime() == Qualifiers::OCL_Weak)
17809  }
17810 
17811  if (Record && FD->getType().isVolatileQualified())
17812  Record->setHasVolatileMember(true);
17813  // Keep track of the number of named members.
17814  if (FD->getIdentifier())
17815  ++NumNamedMembers;
17816  }
17817 
17818  // Okay, we successfully defined 'Record'.
17819  if (Record) {
17820  bool Completed = false;
17821  if (CXXRecord) {
17822  if (!CXXRecord->isInvalidDecl()) {
17823  // Set access bits correctly on the directly-declared conversions.
17825  I = CXXRecord->conversion_begin(),
17826  E = CXXRecord->conversion_end(); I != E; ++I)
17827  I.setAccess((*I)->getAccess());
17828  }
17829 
17830  // Add any implicitly-declared members to this class.
17831  AddImplicitlyDeclaredMembersToClass(CXXRecord);
17832 
17833  if (!CXXRecord->isDependentType()) {
17834  if (!CXXRecord->isInvalidDecl()) {
17835  // If we have virtual base classes, we may end up finding multiple
17836  // final overriders for a given virtual function. Check for this
17837  // problem now.
17838  if (CXXRecord->getNumVBases()) {
17839  CXXFinalOverriderMap FinalOverriders;
17840  CXXRecord->getFinalOverriders(FinalOverriders);
17841 
17842  for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
17843  MEnd = FinalOverriders.end();
17844  M != MEnd; ++M) {
17845  for (OverridingMethods::iterator SO = M->second.begin(),
17846  SOEnd = M->second.end();
17847  SO != SOEnd; ++SO) {
17848  assert(SO->second.size() > 0 &&
17849  "Virtual function without overriding functions?");
17850  if (SO->second.size() == 1)
17851  continue;
17852 
17853  // C++ [class.virtual]p2:
17854  // In a derived class, if a virtual member function of a base
17855  // class subobject has more than one final overrider the
17856  // program is ill-formed.
17857  Diag(Record->getLocation(), diag::err_multiple_final_overriders)
17858  << (const NamedDecl *)M->first << Record;
17859  Diag(M->first->getLocation(),
17860  diag::note_overridden_virtual_function);
17862  OM = SO->second.begin(),
17863  OMEnd = SO->second.end();
17864  OM != OMEnd; ++OM)
17865  Diag(OM->Method->getLocation(), diag::note_final_overrider)
17866  << (const NamedDecl *)M->first << OM->Method->getParent();
17867 
17868  Record->setInvalidDecl();
17869  }
17870  }
17871  CXXRecord->completeDefinition(&FinalOverriders);
17872  Completed = true;
17873  }
17874  }
17875  }
17876  }
17877 
17878  if (!Completed)
17879  Record->completeDefinition();
17880 
17881  // Handle attributes before checking the layout.
17882  ProcessDeclAttributeList(S, Record, Attrs);
17883 
17884  // We may have deferred checking for a deleted destructor. Check now.
17885  if (CXXRecord) {
17886  auto *Dtor = CXXRecord->getDestructor();
17887  if (Dtor && Dtor->isImplicit() &&
17888  ShouldDeleteSpecialMember(Dtor, CXXDestructor)) {
17889  CXXRecord->setImplicitDestructorIsDeleted();
17890  SetDeclDeleted(Dtor, CXXRecord->getLocation());
17891  }
17892  }
17893 
17894  if (Record->hasAttrs()) {
17895  CheckAlignasUnderalignment(Record);
17896 
17897  if (const MSInheritanceAttr *IA = Record->getAttr<MSInheritanceAttr>())
17898  checkMSInheritanceAttrOnDefinition(cast<CXXRecordDecl>(Record),
17899  IA->getRange(), IA->getBestCase(),
17900  IA->getInheritanceModel());
17901  }
17902 
17903  // Check if the structure/union declaration is a type that can have zero
17904  // size in C. For C this is a language extension, for C++ it may cause
17905  // compatibility problems.
17906  bool CheckForZeroSize;
17907  if (!getLangOpts().CPlusPlus) {
17908  CheckForZeroSize = true;
17909  } else {
17910  // For C++ filter out types that cannot be referenced in C code.
17911  CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
17912  CheckForZeroSize =
17913  CXXRecord->getLexicalDeclContext()->isExternCContext() &&
17914  !CXXRecord->isDependentType() && !inTemplateInstantiation() &&
17915  CXXRecord->isCLike();
17916  }
17917  if (CheckForZeroSize) {
17918  bool ZeroSize = true;
17919  bool IsEmpty = true;
17920  unsigned NonBitFields = 0;
17921  for (RecordDecl::field_iterator I = Record->field_begin(),
17922  E = Record->field_end();
17923  (NonBitFields == 0 || ZeroSize) && I != E; ++I) {
17924  IsEmpty = false;
17925  if (I->isUnnamedBitfield()) {
17926  if (!I->isZeroLengthBitField(Context))
17927  ZeroSize = false;
17928  } else {
17929  ++NonBitFields;
17930  QualType FieldType = I->getType();
17931  if (FieldType->isIncompleteType() ||
17932  !Context.getTypeSizeInChars(FieldType).isZero())
17933  ZeroSize = false;
17934  }
17935  }
17936 
17937  // Empty structs are an extension in C (C99 6.7.2.1p7). They are
17938  // allowed in C++, but warn if its declaration is inside
17939  // extern "C" block.
17940  if (ZeroSize) {
17941  Diag(RecLoc, getLangOpts().CPlusPlus ?
17942  diag::warn_zero_size_struct_union_in_extern_c :
17943  diag::warn_zero_size_struct_union_compat)
17944  << IsEmpty << Record->isUnion() << (NonBitFields > 1);
17945  }
17946 
17947  // Structs without named members are extension in C (C99 6.7.2.1p7),
17948  // but are accepted by GCC.
17949  if (NonBitFields == 0 && !getLangOpts().CPlusPlus) {
17950  Diag(RecLoc, IsEmpty ? diag::ext_empty_struct_union :
17951  diag::ext_no_named_members_in_struct_union)
17952  << Record->isUnion();
17953  }
17954  }
17955  } else {
17956  ObjCIvarDecl **ClsFields =
17957  reinterpret_cast<ObjCIvarDecl**>(RecFields.data());
17958  if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
17959  ID->setEndOfDefinitionLoc(RBrac);
17960  // Add ivar's to class's DeclContext.
17961  for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17962  ClsFields[i]->setLexicalDeclContext(ID);
17963  ID->addDecl(ClsFields[i]);
17964  }
17965  // Must enforce the rule that ivars in the base classes may not be
17966  // duplicates.
17967  if (ID->getSuperClass())
17968  DiagnoseDuplicateIvars(ID, ID->getSuperClass());
17969  } else if (ObjCImplementationDecl *IMPDecl =
17970  dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
17971  assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
17972  for (unsigned I = 0, N = RecFields.size(); I != N; ++I)
17973  // Ivar declared in @implementation never belongs to the implementation.
17974  // Only it is in implementation's lexical context.
17975  ClsFields[I]->setLexicalDeclContext(IMPDecl);
17976  CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
17977  IMPDecl->setIvarLBraceLoc(LBrac);
17978  IMPDecl->setIvarRBraceLoc(RBrac);
17979  } else if (ObjCCategoryDecl *CDecl =
17980  dyn_cast<ObjCCategoryDecl>(EnclosingDecl)) {
17981  // case of ivars in class extension; all other cases have been
17982  // reported as errors elsewhere.
17983  // FIXME. Class extension does not have a LocEnd field.
17984  // CDecl->setLocEnd(RBrac);
17985  // Add ivar's to class extension's DeclContext.
17986  // Diagnose redeclaration of private ivars.
17987  ObjCInterfaceDecl *IDecl = CDecl->getClassInterface();
17988  for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
17989  if (IDecl) {
17990  if (const ObjCIvarDecl *ClsIvar =
17991  IDecl->getIvarDecl(ClsFields[i]->getIdentifier())) {
17992  Diag(ClsFields[i]->getLocation(),
17993  diag::err_duplicate_ivar_declaration);
17994  Diag(ClsIvar->getLocation(), diag::note_previous_definition);
17995  continue;
17996  }
17997  for (const auto *Ext : IDecl->known_extensions()) {
17998  if (const ObjCIvarDecl *ClsExtIvar
17999  = Ext->getIvarDecl(ClsFields[i]->getIdentifier())) {
18000  Diag(ClsFields[i]->getLocation(),
18001  diag::err_duplicate_ivar_declaration);
18002  Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
18003  continue;
18004  }
18005  }
18006  }
18007  ClsFields[i]->setLexicalDeclContext(CDecl);
18008  CDecl->addDecl(ClsFields[i]);
18009  }
18010  CDecl->setIvarLBraceLoc(LBrac);
18011  CDecl->setIvarRBraceLoc(RBrac);
18012  }
18013  }
18014 }
18015 
18016 /// Determine whether the given integral value is representable within
18017 /// the given type T.
18020  QualType T) {
18021  assert((T->isIntegralType(Context) || T->isEnumeralType()) &&
18022  "Integral type required!");
18023  unsigned BitWidth = Context.getIntWidth(T);
18024 
18025  if (Value.isUnsigned() || Value.isNonNegative()) {
18027  --BitWidth;
18028  return Value.getActiveBits() <= BitWidth;
18029  }
18030  return Value.getMinSignedBits() <= BitWidth;
18031 }
18032 
18033 // Given an integral type, return the next larger integral type
18034 // (or a NULL type of no such type exists).
18036  // FIXME: Int128/UInt128 support, which also needs to be introduced into
18037  // enum checking below.
18038  assert((T->isIntegralType(Context) ||
18039  T->isEnumeralType()) && "Integral type required!");
18040  const unsigned NumTypes = 4;
18041  QualType SignedIntegralTypes[NumTypes] = {
18042  Context.ShortTy, Context.IntTy, Context.LongTy, Context.LongLongTy
18043  };
18044  QualType UnsignedIntegralTypes[NumTypes] = {
18045  Context.UnsignedShortTy, Context.UnsignedIntTy, Context.UnsignedLongTy,
18046  Context.UnsignedLongLongTy
18047  };
18048 
18049  unsigned BitWidth = Context.getTypeSize(T);
18050  QualType *Types = T->isSignedIntegerOrEnumerationType()? SignedIntegralTypes
18051  : UnsignedIntegralTypes;
18052  for (unsigned I = 0; I != NumTypes; ++I)
18053  if (Context.getTypeSize(Types[I]) > BitWidth)
18054  return Types[I];
18055 
18056  return QualType();
18057 }
18058 
18060  EnumConstantDecl *LastEnumConst,
18061  SourceLocation IdLoc,
18062  IdentifierInfo *Id,
18063  Expr *Val) {
18064  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18065  llvm::APSInt EnumVal(IntWidth);
18066  QualType EltTy;
18067 
18068  if (Val && DiagnoseUnexpandedParameterPack(Val, UPPC_EnumeratorValue))
18069  Val = nullptr;
18070 
18071  if (Val)
18072  Val = DefaultLvalueConversion(Val).get();
18073 
18074  if (Val) {
18075  if (Enum->isDependentType() || Val->isTypeDependent() ||
18076  Val->containsErrors())
18077  EltTy = Context.DependentTy;
18078  else {
18079  // FIXME: We don't allow folding in C++11 mode for an enum with a fixed
18080  // underlying type, but do allow it in all other contexts.
18081  if (getLangOpts().CPlusPlus11 && Enum->isFixed()) {
18082  // C++11 [dcl.enum]p5: If the underlying type is fixed, [...] the
18083  // constant-expression in the enumerator-definition shall be a converted
18084  // constant expression of the underlying type.
18085  EltTy = Enum->getIntegerType();
18086  ExprResult Converted =
18087  CheckConvertedConstantExpression(Val, EltTy, EnumVal,
18088  CCEK_Enumerator);
18089  if (Converted.isInvalid())
18090  Val = nullptr;
18091  else
18092  Val = Converted.get();
18093  } else if (!Val->isValueDependent() &&
18094  !(Val =
18095  VerifyIntegerConstantExpression(Val, &EnumVal, AllowFold)
18096  .get())) {
18097  // C99 6.7.2.2p2: Make sure we have an integer constant expression.
18098  } else {
18099  if (Enum->isComplete()) {
18100  EltTy = Enum->getIntegerType();
18101 
18102  // In Obj-C and Microsoft mode, require the enumeration value to be
18103  // representable in the underlying type of the enumeration. In C++11,
18104  // we perform a non-narrowing conversion as part of converted constant
18105  // expression checking.
18106  if (!isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18107  if (Context.getTargetInfo()
18108  .getTriple()
18109  .isWindowsMSVCEnvironment()) {
18110  Diag(IdLoc, diag::ext_enumerator_too_large) << EltTy;
18111  } else {
18112  Diag(IdLoc, diag::err_enumerator_too_large) << EltTy;
18113  }
18114  }
18115 
18116  // Cast to the underlying type.
18117  Val = ImpCastExprToType(Val, EltTy,
18118  EltTy->isBooleanType() ? CK_IntegralToBoolean
18119  : CK_IntegralCast)
18120  .get();
18121  } else if (getLangOpts().CPlusPlus) {
18122  // C++11 [dcl.enum]p5:
18123  // If the underlying type is not fixed, the type of each enumerator
18124  // is the type of its initializing value:
18125  // - If an initializer is specified for an enumerator, the
18126  // initializing value has the same type as the expression.
18127  EltTy = Val->getType();
18128  } else {
18129  // C99 6.7.2.2p2:
18130  // The expression that defines the value of an enumeration constant
18131  // shall be an integer constant expression that has a value
18132  // representable as an int.
18133 
18134  // Complain if the value is not representable in an int.
18135  if (!isRepresentableIntegerValue(Context, EnumVal, Context.IntTy))
18136  Diag(IdLoc, diag::ext_enum_value_not_int)
18137  << toString(EnumVal, 10) << Val->getSourceRange()
18138  << (EnumVal.isUnsigned() || EnumVal.isNonNegative());
18139  else if (!Context.hasSameType(Val->getType(), Context.IntTy)) {
18140  // Force the type of the expression to 'int'.
18141  Val = ImpCastExprToType(Val, Context.IntTy, CK_IntegralCast).get();
18142  }
18143  EltTy = Val->getType();
18144  }
18145  }
18146  }
18147  }
18148 
18149  if (!Val) {
18150  if (Enum->isDependentType())
18151  EltTy = Context.DependentTy;
18152  else if (!LastEnumConst) {
18153  // C++0x [dcl.enum]p5:
18154  // If the underlying type is not fixed, the type of each enumerator
18155  // is the type of its initializing value:
18156  // - If no initializer is specified for the first enumerator, the
18157  // initializing value has an unspecified integral type.
18158  //
18159  // GCC uses 'int' for its unspecified integral type, as does
18160  // C99 6.7.2.2p3.
18161  if (Enum->isFixed()) {
18162  EltTy = Enum->getIntegerType();
18163  }
18164  else {
18165  EltTy = Context.IntTy;
18166  }
18167  } else {
18168  // Assign the last value + 1.
18169  EnumVal = LastEnumConst->getInitVal();
18170  ++EnumVal;
18171  EltTy = LastEnumConst->getType();
18172 
18173  // Check for overflow on increment.
18174  if (EnumVal < LastEnumConst->getInitVal()) {
18175  // C++0x [dcl.enum]p5:
18176  // If the underlying type is not fixed, the type of each enumerator
18177  // is the type of its initializing value:
18178  //
18179  // - Otherwise the type of the initializing value is the same as
18180  // the type of the initializing value of the preceding enumerator
18181  // unless the incremented value is not representable in that type,
18182  // in which case the type is an unspecified integral type
18183  // sufficient to contain the incremented value. If no such type
18184  // exists, the program is ill-formed.
18185  QualType T = getNextLargerIntegralType(Context, EltTy);
18186  if (T.isNull() || Enum->isFixed()) {
18187  // There is no integral type larger enough to represent this
18188  // value. Complain, then allow the value to wrap around.
18189  EnumVal = LastEnumConst->getInitVal();
18190  EnumVal = EnumVal.zext(EnumVal.getBitWidth() * 2);
18191  ++EnumVal;
18192  if (Enum->isFixed())
18193  // When the underlying type is fixed, this is ill-formed.
18194  Diag(IdLoc, diag::err_enumerator_wrapped)
18195  << toString(EnumVal, 10)
18196  << EltTy;
18197  else
18198  Diag(IdLoc, diag::ext_enumerator_increment_too_large)
18199  << toString(EnumVal, 10);
18200  } else {
18201  EltTy = T;
18202  }
18203 
18204  // Retrieve the last enumerator's value, extent that type to the
18205  // type that is supposed to be large enough to represent the incremented
18206  // value, then increment.
18207  EnumVal = LastEnumConst->getInitVal();
18208  EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18209  EnumVal = EnumVal.zextOrTrunc(Context.getIntWidth(EltTy));
18210  ++EnumVal;
18211 
18212  // If we're not in C++, diagnose the overflow of enumerator values,
18213  // which in C99 means that the enumerator value is not representable in
18214  // an int (C99 6.7.2.2p2). However, we support GCC's extension that
18215  // permits enumerator values that are representable in some larger
18216  // integral type.
18217  if (!getLangOpts().CPlusPlus && !T.isNull())
18218  Diag(IdLoc, diag::warn_enum_value_overflow);
18219  } else if (!getLangOpts().CPlusPlus &&
18220  !isRepresentableIntegerValue(Context, EnumVal, EltTy)) {
18221  // Enforce C99 6.7.2.2p2 even when we compute the next value.
18222  Diag(IdLoc, diag::ext_enum_value_not_int)
18223  << toString(EnumVal, 10) << 1;
18224  }
18225  }
18226  }
18227 
18228  if (!EltTy->isDependentType()) {
18229  // Make the enumerator value match the signedness and size of the
18230  // enumerator's type.
18231  EnumVal = EnumVal.extOrTrunc(Context.getIntWidth(EltTy));
18232  EnumVal.setIsSigned(EltTy->isSignedIntegerOrEnumerationType());
18233  }
18234 
18235  return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
18236  Val, EnumVal);
18237 }
18238 
18240  SourceLocation IILoc) {
18241  if (!(getLangOpts().Modules || getLangOpts().ModulesLocalVisibility) ||
18242  !getLangOpts().CPlusPlus)
18243  return SkipBodyInfo();
18244 
18245  // We have an anonymous enum definition. Look up the first enumerator to
18246  // determine if we should merge the definition with an existing one and
18247  // skip the body.
18248  NamedDecl *PrevDecl = LookupSingleName(S, II, IILoc, LookupOrdinaryName,
18249  forRedeclarationInCurContext());
18250  auto *PrevECD = dyn_cast_or_null<EnumConstantDecl>(PrevDecl);
18251  if (!PrevECD)
18252  return SkipBodyInfo();
18253 
18254  EnumDecl *PrevED = cast<EnumDecl>(PrevECD->getDeclContext());
18255  NamedDecl *Hidden;
18256  if (!PrevED->getDeclName() && !hasVisibleDefinition(PrevED, &Hidden)) {
18257  SkipBodyInfo Skip;
18258  Skip.Previous = Hidden;
18259  return Skip;
18260  }
18261 
18262  return SkipBodyInfo();
18263 }
18264 
18265 Decl *Sema::ActOnEnumConstant(Scope *S, Decl *theEnumDecl, Decl *lastEnumConst,
18267  const ParsedAttributesView &Attrs,
18268  SourceLocation EqualLoc, Expr *Val) {
18269  EnumDecl *TheEnumDecl = cast<EnumDecl>(theEnumDecl);
18270  EnumConstantDecl *LastEnumConst =
18271  cast_or_null<EnumConstantDecl>(lastEnumConst);
18272 
18273  // The scope passed in may not be a decl scope. Zip up the scope tree until
18274  // we find one that is.
18275  S = getNonFieldDeclScope(S);
18276 
18277  // Verify that there isn't already something declared with this name in this
18278  // scope.
18279  LookupResult R(*this, Id, IdLoc, LookupOrdinaryName, ForVisibleRedeclaration);
18280  LookupName(R, S);
18281  NamedDecl *PrevDecl = R.getAsSingle<NamedDecl>();
18282 
18283  if (PrevDecl && PrevDecl->isTemplateParameter()) {
18284  // Maybe we will complain about the shadowed template parameter.
18285  DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
18286  // Just pretend that we didn't see the previous declaration.
18287  PrevDecl = nullptr;
18288  }
18289 
18290  // C++ [class.mem]p15:
18291  // If T is the name of a class, then each of the following shall have a name
18292  // different from T:
18293  // - every enumerator of every member of class T that is an unscoped
18294  // enumerated type
18295  if (getLangOpts().CPlusPlus && !TheEnumDecl->isScoped())
18296  DiagnoseClassNameShadow(TheEnumDecl->getDeclContext(),
18297  DeclarationNameInfo(Id, IdLoc));
18298 
18299  EnumConstantDecl *New =
18300  CheckEnumConstant(TheEnumDecl, LastEnumConst, IdLoc, Id, Val);
18301  if (!New)
18302  return nullptr;
18303 
18304  if (PrevDecl) {
18305  if (!TheEnumDecl->isScoped() && isa<ValueDecl>(PrevDecl)) {
18306  // Check for other kinds of shadowing not already handled.
18307  CheckShadow(New, PrevDecl, R);
18308  }
18309 
18310  // When in C++, we may get a TagDecl with the same name; in this case the
18311  // enum constant will 'hide' the tag.
18312  assert((getLangOpts().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
18313  "Received TagDecl when not in C++!");
18314  if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
18315  if (isa<EnumConstantDecl>(PrevDecl))
18316  Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
18317  else
18318  Diag(IdLoc, diag::err_redefinition) << Id;
18319  notePreviousDefinition(PrevDecl, IdLoc);
18320  return nullptr;
18321  }
18322  }
18323 
18324  // Process attributes.
18325  ProcessDeclAttributeList(S, New, Attrs);
18326  AddPragmaAttributes(S, New);
18327 
18328  // Register this decl in the current scope stack.
18329  New->setAccess(TheEnumDecl->getAccess());
18330  PushOnScopeChains(New, S);
18331 
18332  ActOnDocumentableDecl(New);
18333 
18334  return New;
18335 }
18336 
18337 // Returns true when the enum initial expression does not trigger the
18338 // duplicate enum warning. A few common cases are exempted as follows:
18339 // Element2 = Element1
18340 // Element2 = Element1 + 1
18341 // Element2 = Element1 - 1
18342 // Where Element2 and Element1 are from the same enum.
18344  Expr *InitExpr = ECD->getInitExpr();
18345  if (!InitExpr)
18346  return true;
18347  InitExpr = InitExpr->IgnoreImpCasts();
18348 
18349  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(InitExpr)) {
18350  if (!BO->isAdditiveOp())
18351  return true;
18352  IntegerLiteral *IL = dyn_cast<IntegerLiteral>(BO->getRHS());
18353  if (!IL)
18354  return true;
18355  if (IL->getValue() != 1)
18356  return true;
18357 
18358  InitExpr = BO->getLHS();
18359  }
18360 
18361  // This checks if the elements are from the same enum.
18362  DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(InitExpr);
18363  if (!DRE)
18364  return true;
18365 
18366  EnumConstantDecl *EnumConstant = dyn_cast<EnumConstantDecl>(DRE->getDecl());
18367  if (!EnumConstant)
18368  return true;
18369 
18370  if (cast<EnumDecl>(TagDecl::castFromDeclContext(ECD->getDeclContext())) !=
18371  Enum)
18372  return true;
18373 
18374  return false;
18375 }
18376 
18377 // Emits a warning when an element is implicitly set a value that
18378 // a previous element has already been set to.
18380  EnumDecl *Enum, QualType EnumType) {
18381  // Avoid anonymous enums
18382  if (!Enum->getIdentifier())
18383  return;
18384 
18385  // Only check for small enums.
18386  if (Enum->getNumPositiveBits() > 63 || Enum->getNumNegativeBits() > 64)
18387  return;
18388 
18389  if (S.Diags.isIgnored(diag::warn_duplicate_enum_values, Enum->getLocation()))
18390  return;
18391 
18392  typedef SmallVector<EnumConstantDecl *, 3> ECDVector;
18393  typedef SmallVector<std::unique_ptr<ECDVector>, 3> DuplicatesVector;
18394 
18395  typedef llvm::PointerUnion<EnumConstantDecl*, ECDVector*> DeclOrVector;
18396 
18397  // DenseMaps cannot contain the all ones int64_t value, so use unordered_map.
18398  typedef std::unordered_map<int64_t, DeclOrVector> ValueToVectorMap;
18399 
18400  // Use int64_t as a key to avoid needing special handling for map keys.
18401  auto EnumConstantToKey = [](const EnumConstantDecl *D) {
18402  llvm::APSInt Val = D->getInitVal();
18403  return Val.isSigned() ? Val.getSExtValue() : Val.getZExtValue();
18404  };
18405 
18406  DuplicatesVector DupVector;
18407  ValueToVectorMap EnumMap;
18408 
18409  // Populate the EnumMap with all values represented by enum constants without
18410  // an initializer.
18411  for (auto *Element : Elements) {
18412  EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(Element);
18413 
18414  // Null EnumConstantDecl means a previous diagnostic has been emitted for
18415  // this constant. Skip this enum since it may be ill-formed.
18416  if (!ECD) {
18417  return;
18418  }
18419 
18420  // Constants with initalizers are handled in the next loop.
18421  if (ECD->getInitExpr())
18422  continue;
18423 
18424  // Duplicate values are handled in the next loop.
18425  EnumMap.insert({EnumConstantToKey(ECD), ECD});
18426  }
18427 
18428  if (EnumMap.size() == 0)
18429  return;
18430 
18431  // Create vectors for any values that has duplicates.
18432  for (auto *Element : Elements) {
18433  // The last loop returned if any constant was null.
18434  EnumConstantDecl *ECD = cast<EnumConstantDecl>(Element);
18435  if (!ValidDuplicateEnum(ECD, Enum))
18436  continue;
18437 
18438  auto Iter = EnumMap.find(EnumConstantToKey(ECD));
18439  if (Iter == EnumMap.end())
18440  continue;
18441 
18442  DeclOrVector& Entry = Iter->second;
18443  if (EnumConstantDecl *D = Entry.dyn_cast<EnumConstantDecl*>()) {
18444  // Ensure constants are different.
18445  if (D == ECD)
18446  continue;
18447 
18448  // Create new vector and push values onto it.
18449  auto Vec = std::make_unique<ECDVector>();
18450  Vec->push_back(D);
18451  Vec->push_back(ECD);
18452 
18453  // Update entry to point to the duplicates vector.
18454  Entry = Vec.get();
18455 
18456  // Store the vector somewhere we can consult later for quick emission of
18457  // diagnostics.
18458  DupVector.emplace_back(std::move(Vec));
18459  continue;
18460  }
18461 
18462  ECDVector *Vec = Entry.get<ECDVector*>();
18463  // Make sure constants are not added more than once.
18464  if (*Vec->begin() == ECD)
18465  continue;
18466 
18467  Vec->push_back(ECD);
18468  }
18469 
18470  // Emit diagnostics.
18471  for (const auto &Vec : DupVector) {
18472  assert(Vec->size() > 1 && "ECDVector should have at least 2 elements.");
18473 
18474  // Emit warning for one enum constant.
18475  auto *FirstECD = Vec->front();
18476  S.Diag(FirstECD->getLocation(), diag::warn_duplicate_enum_values)
18477  << FirstECD << toString(FirstECD->getInitVal(), 10)
18478  << FirstECD->getSourceRange();
18479 
18480  // Emit one note for each of the remaining enum constants with
18481  // the same value.
18482  for (auto *ECD : llvm::drop_begin(*Vec))
18483  S.Diag(ECD->getLocation(), diag::note_duplicate_element)
18484  << ECD << toString(ECD->getInitVal(), 10)
18485  << ECD->getSourceRange();
18486  }
18487 }
18488 
18489 bool Sema::IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val,
18490  bool AllowMask) const {
18491  assert(ED->isClosedFlag() && "looking for value in non-flag or open enum");
18492  assert(ED->isCompleteDefinition() && "expected enum definition");
18493 
18494  auto R = FlagBitsCache.insert(std::make_pair(ED, llvm::APInt()));
18495  llvm::APInt &FlagBits = R.first->second;
18496 
18497  if (R.second) {
18498  for (auto *E : ED->enumerators()) {
18499  const auto &EVal = E->getInitVal();
18500  // Only single-bit enumerators introduce new flag values.
18501  if (EVal.isPowerOf2())
18502  FlagBits = FlagBits.zextOrSelf(EVal.getBitWidth()) | EVal;
18503  }
18504  }
18505 
18506  // A value is in a flag enum if either its bits are a subset of the enum's
18507  // flag bits (the first condition) or we are allowing masks and the same is
18508  // true of its complement (the second condition). When masks are allowed, we
18509  // allow the common idiom of ~(enum1 | enum2) to be a valid enum value.
18510  //
18511  // While it's true that any value could be used as a mask, the assumption is
18512  // that a mask will have all of the insignificant bits set. Anything else is
18513  // likely a logic error.
18514  llvm::APInt FlagMask = ~FlagBits.zextOrTrunc(Val.getBitWidth());
18515  return !(FlagMask & Val) || (AllowMask && !(FlagMask & ~Val));
18516 }
18517 
18519  Decl *EnumDeclX, ArrayRef<Decl *> Elements, Scope *S,
18520  const ParsedAttributesView &Attrs) {
18521  EnumDecl *Enum = cast<EnumDecl>(EnumDeclX);
18522  QualType EnumType = Context.getTypeDeclType(Enum);
18523 
18524  ProcessDeclAttributeList(S, Enum, Attrs);
18525 
18526  if (Enum->isDependentType()) {
18527  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18528  EnumConstantDecl *ECD =
18529  cast_or_null<EnumConstantDecl>(Elements[i]);
18530  if (!ECD) continue;
18531 
18532  ECD->setType(EnumType);
18533  }
18534 
18535  Enum->completeDefinition(Context.DependentTy, Context.DependentTy, 0, 0);
18536  return;
18537  }
18538 
18539  // TODO: If the result value doesn't fit in an int, it must be a long or long
18540  // long value. ISO C does not support this, but GCC does as an extension,
18541  // emit a warning.
18542  unsigned IntWidth = Context.getTargetInfo().getIntWidth();
18543  unsigned CharWidth = Context.getTargetInfo().getCharWidth();
18544  unsigned ShortWidth = Context.getTargetInfo().getShortWidth();
18545 
18546  // Verify that all the values are okay, compute the size of the values, and
18547  // reverse the list.
18548  unsigned NumNegativeBits = 0;
18549  unsigned NumPositiveBits = 0;
18550 
18551  for (unsigned i = 0, e = Elements.size(); i != e; ++i) {
18552  EnumConstantDecl *ECD =
18553  cast_or_null<EnumConstantDecl>(Elements[i]);
18554  if (!ECD) continue; // Already issued a diagnostic.
18555 
18556  const llvm::APSInt &InitVal = ECD->getInitVal();
18557 
18558  // Keep track of the size of positive and negative values.
18559  if (InitVal.isUnsigned() || InitVal.isNonNegative())
18560  NumPositiveBits = std::max(NumPositiveBits,
18561  (unsigned)InitVal.getActiveBits());
18562  else
18563  NumNegativeBits = std::max(NumNegativeBits,
18564  (unsigned)InitVal.getMinSignedBits());
18565  }
18566 
18567  // Figure out the type that should be used for this enum.
18568  QualType BestType;
18569  unsigned BestWidth;
18570 
18571  // C++0x N3000 [conv.prom]p3:
18572  // An rvalue of an unscoped enumeration type whose underlying
18573  // type is not fixed can be converted to an rvalue of the first
18574  // of the following types that can represent all the values of
18575  // the enumeration: int, unsigned int, long int, unsigned long
18576  // int, long long int, or unsigned long long int.
18577  // C99 6.4.4.3p2:
18578  // An identifier declared as an enumeration constant has type int.
18579  // The C99 rule is modified by a gcc extension
18580  QualType BestPromotionType;
18581 
18582  bool Packed = Enum->hasAttr<PackedAttr>();
18583  // -fshort-enums is the equivalent to specifying the packed attribute on all
18584  // enum definitions.
18585  if (LangOpts.ShortEnums)
18586  Packed = true;
18587 
18588  // If the enum already has a type because it is fixed or dictated by the
18589  // target, promote that type instead of analyzing the enumerators.
18590  if (Enum->isComplete()) {
18591  BestType = Enum->getIntegerType();
18592  if (BestType->isPromotableIntegerType())
18593  BestPromotionType = Context.getPromotedIntegerType(BestType);
18594  else
18595  BestPromotionType = BestType;
18596 
18597  BestWidth = Context.getIntWidth(BestType);
18598  }
18599  else if (NumNegativeBits) {
18600  // If there is a negative value, figure out the smallest integer type (of
18601  // int/long/longlong) that fits.
18602  // If it's packed, check also if it fits a char or a short.
18603  if (Packed && NumNegativeBits <= CharWidth && NumPositiveBits < CharWidth) {
18604  BestType = Context.SignedCharTy;
18605  BestWidth = CharWidth;
18606  } else if (Packed && NumNegativeBits <= ShortWidth &&
18607  NumPositiveBits < ShortWidth) {
18608  BestType = Context.ShortTy;
18609  BestWidth = ShortWidth;
18610  } else if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
18611  BestType = Context.IntTy;
18612  BestWidth = IntWidth;
18613  } else {
18614  BestWidth = Context.getTargetInfo().getLongWidth();
18615 
18616  if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth) {
18617  BestType = Context.LongTy;
18618  } else {
18619  BestWidth = Context.getTargetInfo().getLongLongWidth();
18620 
18621  if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
18622  Diag(Enum->getLocation(), diag::ext_enum_too_large);
18623  BestType = Context.LongLongTy;
18624  }
18625  }
18626  BestPromotionType = (BestWidth <= IntWidth ? Context.IntTy : BestType);
18627  } else {
18628  // If there is no negative value, figure out the smallest type that fits
18629  // all of the enumerator values.
18630  // If it's packed, check also if it fits a char or a short.
18631  if (Packed && NumPositiveBits <= CharWidth) {
18632  BestType = Context.UnsignedCharTy;
18633  BestPromotionType = Context.IntTy;
18634  BestWidth = CharWidth;
18635  } else if (Packed && NumPositiveBits <= ShortWidth) {
18636  BestType = Context.UnsignedShortTy;
18637  BestPromotionType = Context.IntTy;
18638  BestWidth = ShortWidth;
18639  } else if (NumPositiveBits <= IntWidth) {
18640  BestType = Context.UnsignedIntTy;
18641  BestWidth = IntWidth;
18642  BestPromotionType
18643  = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18644  ? Context.UnsignedIntTy : Context.IntTy;
18645  } else if (NumPositiveBits <=
18646  (BestWidth = Context.getTargetInfo().getLongWidth())) {
18647  BestType = Context.UnsignedLongTy;
18648  BestPromotionType
18649  = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18650  ? Context.UnsignedLongTy : Context.LongTy;
18651  } else {
18652  BestWidth = Context.getTargetInfo().getLongLongWidth();
18653  assert(NumPositiveBits <= BestWidth &&
18654  "How could an initializer get larger than ULL?");
18655  BestType = Context.UnsignedLongLongTy;
18656  BestPromotionType
18657  = (NumPositiveBits == BestWidth || !getLangOpts().CPlusPlus)
18658  ? Context.UnsignedLongLongTy : Context.LongLongTy;
18659  }
18660  }
18661 
18662  // Loop over all of the enumerator constants, changing their types to match
18663  // the type of the enum if needed.
18664  for (auto *D : Elements) {
18665  auto *ECD = cast_or_null<EnumConstantDecl>(D);
18666  if (!ECD) continue; // Already issued a diagnostic.
18667 
18668  // Standard C says the enumerators have int type, but we allow, as an
18669  // extension, the enumerators to be larger than int size. If each
18670  // enumerator value fits in an int, type it as an int, otherwise type it the
18671  // same as the enumerator decl itself. This means that in "enum { X = 1U }"
18672  // that X has type 'int', not 'unsigned'.
18673 
18674  // Determine whether the value fits into an int.
18675  llvm::APSInt InitVal = ECD->getInitVal();
18676 
18677  // If it fits into an integer type, force it. Otherwise force it to match
18678  // the enum decl type.
18679  QualType NewTy;
18680  unsigned NewWidth;
18681  bool NewSign;
18682  if (!getLangOpts().CPlusPlus &&
18683  !Enum->isFixed() &&
18684  isRepresentableIntegerValue(Context, InitVal, Context.IntTy)) {
18685  NewTy = Context.IntTy;
18686  NewWidth = IntWidth;
18687  NewSign = true;
18688  } else if (ECD->getType() == BestType) {
18689  // Already the right type!
18690  if (getLangOpts().CPlusPlus)
18691  // C++ [dcl.enum]p4: Following the closing brace of an
18692  // enum-specifier, each enumerator has the type of its
18693  // enumeration.
18694  ECD->setType(EnumType);
18695  continue;
18696  } else {
18697  NewTy = BestType;
18698  NewWidth = BestWidth;
18699  NewSign = BestType->isSignedIntegerOrEnumerationType();
18700  }
18701 
18702  // Adjust the APSInt value.
18703  InitVal = InitVal.extOrTrunc(NewWidth);
18704  InitVal.setIsSigned(NewSign);
18705  ECD->setInitVal(InitVal);
18706 
18707  // Adjust the Expr initializer and type.
18708  if (ECD->getInitExpr() &&
18709  !Context.hasSameType(NewTy, ECD->getInitExpr()->getType()))
18710  ECD->setInitExpr(ImplicitCastExpr::Create(
18711  Context, NewTy, CK_IntegralCast, ECD->getInitExpr(),
18712  /*base paths*/ nullptr, VK_PRValue, FPOptionsOverride()));
18713  if (getLangOpts().CPlusPlus)
18714  // C++ [dcl.enum]p4: Following the closing brace of an
18715  // enum-specifier, each enumerator has the type of its
18716  // enumeration.
18717  ECD->setType(EnumType);
18718  else
18719  ECD->setType(NewTy);
18720  }
18721 
18722  Enum->completeDefinition(BestType, BestPromotionType,
18723  NumPositiveBits, NumNegativeBits);
18724 
18725  CheckForDuplicateEnumValues(*this, Elements, Enum, EnumType);
18726 
18727  if (Enum->isClosedFlag()) {
18728  for (Decl *D : Elements) {
18729  EnumConstantDecl *ECD = cast_or_null<EnumConstantDecl>(D);
18730  if (!ECD) continue; // Already issued a diagnostic.
18731 
18732  llvm::APSInt InitVal = ECD->getInitVal();
18733  if (InitVal != 0 && !InitVal.isPowerOf2() &&
18734  !IsValueInFlagEnum(Enum, InitVal, true))
18735  Diag(ECD->getLocation(), diag::warn_flag_enum_constant_out_of_range)
18736  << ECD << Enum;
18737  }
18738  }
18739 
18740  // Now that the enum type is defined, ensure it's not been underaligned.
18741  if (Enum->hasAttrs())
18742  CheckAlignasUnderalignment(Enum);
18743 }
18744 
18746  SourceLocation StartLoc,
18747  SourceLocation EndLoc) {
18748  StringLiteral *AsmString = cast<StringLiteral>(expr);
18749 
18750  FileScopeAsmDecl *New = FileScopeAsmDecl::Create(Context, CurContext,
18751  AsmString, StartLoc,
18752  EndLoc);
18753  CurContext->addDecl(New);
18754  return New;
18755 }
18756 
18758  IdentifierInfo* AliasName,
18759  SourceLocation PragmaLoc,
18760  SourceLocation NameLoc,
18761  SourceLocation AliasNameLoc) {
18762  NamedDecl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc,
18763  LookupOrdinaryName);
18764  AttributeCommonInfo Info(AliasName, SourceRange(AliasNameLoc),
18766  AsmLabelAttr *Attr = AsmLabelAttr::CreateImplicit(
18767  Context, AliasName->getName(), /*IsLiteralLabel=*/true, Info);
18768 
18769  // If a declaration that:
18770  // 1) declares a function or a variable
18771  // 2) has external linkage
18772  // already exists, add a label attribute to it.
18773  if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18774  if (isDeclExternC(PrevDecl))
18775  PrevDecl->addAttr(Attr);
18776  else
18777  Diag(PrevDecl->getLocation(), diag::warn_redefine_extname_not_applied)
18778  << /*Variable*/(isa<FunctionDecl>(PrevDecl) ? 0 : 1) << PrevDecl;
18779  // Otherwise, add a label atttibute to ExtnameUndeclaredIdentifiers.
18780  } else
18781  (void)ExtnameUndeclaredIdentifiers.insert(std::make_pair(Name, Attr));
18782 }
18783 
18785  SourceLocation PragmaLoc,
18786  SourceLocation NameLoc) {
18787  Decl *PrevDecl = LookupSingleName(TUScope, Name, NameLoc, LookupOrdinaryName);
18788 
18789  if (PrevDecl) {
18790  PrevDecl->addAttr(WeakAttr::CreateImplicit(Context, PragmaLoc, AttributeCommonInfo::AS_Pragma));
18791  } else {
18792  (void)WeakUndeclaredIdentifiers[Name].insert(WeakInfo(nullptr, NameLoc));
18793  }
18794 }
18795 
18797  IdentifierInfo* AliasName,
18798  SourceLocation PragmaLoc,
18799  SourceLocation NameLoc,
18800  SourceLocation AliasNameLoc) {
18801  Decl *PrevDecl = LookupSingleName(TUScope, AliasName, AliasNameLoc,
18802  LookupOrdinaryName);
18803  WeakInfo W = WeakInfo(Name, NameLoc);
18804 
18805  if (PrevDecl && (isa<FunctionDecl>(PrevDecl) || isa<VarDecl>(PrevDecl))) {
18806  if (!PrevDecl->hasAttr<AliasAttr>())
18807  if (NamedDecl *ND = dyn_cast<NamedDecl>(PrevDecl))
18808  DeclApplyPragmaWeak(TUScope, ND, W);
18809  } else {
18810  (void)WeakUndeclaredIdentifiers[AliasName].insert(W);
18811  }
18812 }
18813 
18815  return (dyn_cast_or_null<ObjCContainerDecl>(CurContext));
18816 }
18817 
18819  // FIXME: This should really be a bitwise-or of the language modes.
18820  if (FD->hasAttr<SYCLSimdAttr>())
18822  if (FD->hasAttr<SYCLDeviceAttr>() || FD->hasAttr<SYCLKernelAttr>())
18824  // FIXME: Refine the logic for CUDA and OpenMP.
18825  if (getLangOpts().CUDA)
18826  return getLangOpts().CUDAIsDevice ? Sema::DeviceDiagnosticReason::CudaDevice
18828  if (getLangOpts().OpenMP)
18829  return getLangOpts().OpenMPIsDevice
18833 }
18834 
18836  bool Final) {
18837  assert(FD && "Expected non-null FunctionDecl");
18838 
18839  // Templates are emitted when they're instantiated.
18840  if (FD->isDependentContext())
18841  return FunctionEmissionStatus::TemplateDiscarded;
18842 
18843  if (LangOpts.SYCLIsDevice &&
18844  (FD->hasAttr<SYCLDeviceAttr>() || FD->hasAttr<SYCLKernelAttr>()))
18845  return FunctionEmissionStatus::Emitted;
18846 
18847  // Check whether this function is an externally visible definition.
18848  auto IsEmittedForExternalSymbol = [this, FD]() {
18849  // We have to check the GVA linkage of the function's *definition* -- if we
18850  // only have a declaration, we don't know whether or not the function will
18851  // be emitted, because (say) the definition could include "inline".
18852  FunctionDecl *Def = FD->getDefinition();
18853 
18854  return Def && !isDiscardableGVALinkage(
18855  getASTContext().GetGVALinkageForFunction(Def));
18856  };
18857 
18858  if (LangOpts.OpenMPIsDevice) {
18859  // In OpenMP device mode we will not emit host only functions, or functions
18860  // we don't need due to their linkage.
18862  OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18863  // DevTy may be changed later by
18864  // #pragma omp declare target to(*) device_type(*).
18865  // Therefore DevTy having no value does not imply host. The emission status
18866  // will be checked again at the end of compilation unit with Final = true.
18867  if (DevTy.hasValue())
18868  if (*DevTy == OMPDeclareTargetDeclAttr::DT_Host)
18869  return FunctionEmissionStatus::OMPDiscarded;
18870  // If we have an explicit value for the device type, or we are in a target
18871  // declare context, we need to emit all extern and used symbols.
18872  if (isInOpenMPDeclareTargetContext() || DevTy.hasValue())
18873  if (IsEmittedForExternalSymbol())
18874  return FunctionEmissionStatus::Emitted;
18875  // Device mode only emits what it must, if it wasn't tagged yet and needed,
18876  // we'll omit it.
18877  if (Final)
18878  return FunctionEmissionStatus::OMPDiscarded;
18879  } else if (LangOpts.OpenMP > 45) {
18880  // In OpenMP host compilation prior to 5.0 everything was an emitted host
18881  // function. In 5.0, no_host was introduced which might cause a function to
18882  // be ommitted.
18884  OMPDeclareTargetDeclAttr::getDeviceType(FD->getCanonicalDecl());
18885  if (DevTy.hasValue())
18886  if (*DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
18887  return FunctionEmissionStatus::OMPDiscarded;
18888  }
18889 
18890  if (Final && LangOpts.OpenMP && !LangOpts.CUDA)
18891  return FunctionEmissionStatus::Emitted;
18892 
18893  if (LangOpts.CUDA) {
18894  // When compiling for device, host functions are never emitted. Similarly,
18895  // when compiling for host, device and global functions are never emitted.
18896  // (Technically, we do emit a host-side stub for global functions, but this
18897  // doesn't count for our purposes here.)
18898  Sema::CUDAFunctionTarget T = IdentifyCUDATarget(FD);
18899  if (LangOpts.CUDAIsDevice && T == Sema::CFT_Host)
18900  return FunctionEmissionStatus::CUDADiscarded;
18901  if (!LangOpts.CUDAIsDevice &&
18902  (T == Sema::CFT_Device || T == Sema::CFT_Global))
18903  return FunctionEmissionStatus::CUDADiscarded;
18904 
18905  if (IsEmittedForExternalSymbol())
18906  return FunctionEmissionStatus::Emitted;
18907  }
18908 
18909  if (getLangOpts().SYCLIsDevice) {
18910  if (!FD->hasAttr<SYCLDeviceAttr>() && !FD->hasAttr<SYCLKernelAttr>())
18912 
18913  // Check whether this function is externally visible -- if so, it's
18914  // known-emitted.
18915  //
18916  // We have to check the GVA linkage of the function's *definition* -- if we
18917  // only have a declaration, we don't know whether or not the function will
18918  // be emitted, because (say) the definition could include "inline".
18919  FunctionDecl *Def = FD->getDefinition();
18920 
18921  if (Def &&
18922  !isDiscardableGVALinkage(getASTContext().GetGVALinkageForFunction(Def)))
18923  return FunctionEmissionStatus::Emitted;
18924  }
18925 
18926  // Otherwise, the function is known-emitted if it's in our set of
18927  // known-emitted functions.
18929 }
18930 
18932  // Host-side references to a __global__ function refer to the stub, so the
18933  // function itself is never emitted and therefore should not be marked.
18934  // If we have host fn calls kernel fn calls host+device, the HD function
18935  // does not get instantiated on the host. We model this by omitting at the
18936  // call to the kernel from the callgraph. This ensures that, when compiling
18937  // for host, only HD functions actually called from the host get marked as
18938  // known-emitted.
18939  return LangOpts.CUDA && !LangOpts.CUDAIsDevice &&
18940  IdentifyCUDATarget(Callee) == CFT_Global;
18941 }
clang::OpenCL
@ OpenCL
Definition: LangStandard.h:58
clang::Type::isIntegralType
bool isIntegralType(const ASTContext &Ctx) const
Determine whether this type is an integral type.
Definition: Type.cpp:1931
clang::Decl::setLexicalDeclContext
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:331
diagnoseMissingConstinit
static void diagnoseMissingConstinit(Sema &S, const VarDecl *InitDecl, const ConstInitAttr *CIAttr, bool AttrBeforeInit)
Definition: SemaDecl.cpp:2976
clang::QualifierCollector::strip
const Type * strip(QualType type)
Collect any qualifiers on the given type and return an unqualified type.
Definition: Type.h:6449
clang::Sema::MergeIntelNamedSubGroupSizeAttr
IntelNamedSubGroupSizeAttr * MergeIntelNamedSubGroupSizeAttr(Decl *D, const IntelNamedSubGroupSizeAttr &A)
clang::BuiltinType
This class is used for builtin types like 'int'.
Definition: Type.h:2502
diagnoseImplicitlyRetainedSelf
static void diagnoseImplicitlyRetainedSelf(Sema &S)
Definition: SemaDecl.cpp:14693
clang::FunctionDecl::getSourceRange
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:4049
clang::FunctionDefinitionKind::Defaulted
@ Defaulted
hasDeducedAuto
static bool hasDeducedAuto(DeclaratorDecl *DD)
Definition: SemaDecl.cpp:13760
clang::DeclaratorDecl::getInnerLocStart
SourceLocation getInnerLocStart() const
Return start of source range ignoring outer template declarations.
Definition: Decl.h:770
clang::NestedNameSpecifier::Create
static NestedNameSpecifier * Create(const ASTContext &Context, NestedNameSpecifier *Prefix, IdentifierInfo *II)
Builds a specifier combining a prefix and an identifier.
Definition: NestedNameSpecifier.cpp:59
clang::ExplicitSpecifier
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1815
clang::DeclarationNameInfo::setCXXLiteralOperatorNameLoc
void setCXXLiteralOperatorNameLoc(SourceLocation Loc)
setCXXLiteralOperatorNameLoc - Sets the location of the literal operator name (not the operator keywo...
Definition: DeclarationName.h:839
clang::EnumDecl::setIntegerTypeSourceInfo
void setIntegerTypeSourceInfo(TypeSourceInfo *TInfo)
Set the underlying integer type source info.
Definition: Decl.h:3784
clang::Sema::CheckShadow
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
Definition: SemaDecl.cpp:7865
clang::DeclSpec::getVirtualSpecLoc
SourceLocation getVirtualSpecLoc() const
Definition: DeclSpec.h:579
clang::InternalLinkage
@ InternalLinkage
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:31
clang::TagDecl::hasNameForLinkage
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3556
clang::Sema::MergeIntelFPGABankWidthAttr
IntelFPGABankWidthAttr * MergeIntelFPGABankWidthAttr(Decl *D, const IntelFPGABankWidthAttr &A)
clang::Language::CUDA
@ CUDA
clang::DeclaratorChunk::FunctionTypeInfo::NumParams
unsigned NumParams
NumParams - This is the number of formal parameters specified by the declarator.
Definition: DeclSpec.h:1315
clang::ObjCInterfaceDecl
Represents an ObjC class declaration.
Definition: DeclObjC.h:1150
clang::UnqualifiedId
Represents a C++ unqualified-id that has been parsed.
Definition: DeclSpec.h:950
clang::RecordDecl::hasFlexibleArrayMember
bool hasFlexibleArrayMember() const
Definition: Decl.h:3939
clang::sema::CapturingScopeInfo::addCapture
void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:693
clang::FunctionNoProtoTypeLoc
Definition: TypeLoc.h:1504
clang::ASTContext::getTypeSizeInChars
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
Definition: ASTContext.cpp:2472
clang::FunctionDecl::getMultiVersionKind
MultiVersionKind getMultiVersionKind() const
Gets the kind of multiversioning attribute this declaration has.
Definition: Decl.cpp:3284
clang::VarDecl::TentativeDefinition
@ TentativeDefinition
This declaration is a tentative definition.
Definition: Decl.h:1214
clang::Type::getObjCARCImplicitLifetime
Qualifiers::ObjCLifetime getObjCARCImplicitLifetime() const
Return the implicit lifetime for this type, which must not be dependent.
Definition: Type.cpp:4280
clang::Sema::CurContext
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:599
clang::Type::getNullability
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Definition: Type.cpp:4073
clang::Type::isSamplerT
bool isSamplerT() const
Definition: Type.h:6951
clang::ReturnStmt::setNRVOCandidate
void setNRVOCandidate(const VarDecl *Var)
Set the variable that might be used for the named return value optimization.
Definition: Stmt.h:2815
clang::ASTContext::getQualifiedType
QualType getQualifiedType(SplitQualType split) const
Un-split a SplitQualType.
Definition: ASTContext.h:2123
Builtins.h
clang::DeclaratorChunk::FunctionTypeInfo::hasPrototype
unsigned hasPrototype
hasPrototype - This is true if the function had at least one typed parameter.
Definition: DeclSpec.h:1280
clang::ParenTypeLoc::getInnerLoc
TypeLoc getInnerLoc() const
Definition: TypeLoc.h:1174
clang::FunctionDecl::doesThisDeclarationHaveABody
bool doesThisDeclarationHaveABody() const
Returns whether this specific declaration of the function has a body.
Definition: Decl.h:2163
clang::Declarator::getName
UnqualifiedId & getName()
Retrieve the name specified by this declarator.
Definition: DeclSpec.h:1929
clang::DeclaratorChunk::getReference
static DeclaratorChunk getReference(unsigned TypeQuals, SourceLocation Loc, bool lvalue)
Return a DeclaratorChunk for a reference.
Definition: DeclSpec.h:1597
clang::Type::isRecordType
bool isRecordType() const
Definition: Type.h:6840
clang::QualType::DK_nontrivial_c_struct
@ DK_nontrivial_c_struct
Definition: Type.h:1209
clang::LangAS::opencl_private
@ opencl_private
clang::ObjCCompatibleAliasDecl
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2720
isAcceptableTagRedeclContext
static bool isAcceptableTagRedeclContext(Sema &S, DeclContext *OldDC, DeclContext *NewDC)
Determine whether a tag originally declared in context OldDC can be redeclared with an unqualified na...
Definition: SemaDecl.cpp:15809
clang::FunctionTemplateDecl::mergePrevDecl
void mergePrevDecl(FunctionTemplateDecl *Prev)
Merge Prev with our RedeclarableTemplateDecl::Common.
Definition: DeclTemplate.cpp:412
clang::OpaquePtr::get
PtrTy get() const
Definition: Ownership.h:80
clang::MangleNumberingContext::getManglingNumber
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
clang::Sema::mergeMSInheritanceAttr
MSInheritanceAttr * mergeMSInheritanceAttr(Decl *D, const AttributeCommonInfo &CI, bool BestCase, MSInheritanceModel Model)
max
__DEVICE__ int max(int __a, int __b)
Definition: __clang_cuda_math.h:196
clang::Sema::getNonFieldDeclScope
Scope * getNonFieldDeclScope(Scope *S)
getNonFieldDeclScope - Retrieves the innermost scope, starting from S, where a non-field would be dec...
Definition: SemaDecl.cpp:2170
clang::sema::Capture::getLocation
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:648
clang::isLambdaCallOperator
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
clang::Sema::diagnoseQualifiedDeclaration
bool diagnoseQualifiedDeclaration(CXXScopeSpec &SS, DeclContext *DC, DeclarationName Name, SourceLocation Loc, bool IsTemplateId)
Diagnose a declaration whose declarator-id has the given nested-name-specifier.
Definition: SemaDecl.cpp:5848
clang::LookupResult::NotFound
@ NotFound
No entity found met the criteria.
Definition: Lookup.h:50
clang::FunctionDecl::isDefaulted
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2215
clang::QualType::getObjCLifetime
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1122
clang::Sema::DelayedDiagnostics
A class which encapsulates the logic for delaying diagnostics during parsing and other processing.
Definition: Sema.h:1104
clang::RecordDecl::field_begin
field_iterator field_begin() const
Definition: Decl.cpp:4639
clang::InitializationKind::CreateForInit
static InitializationKind CreateForInit(SourceLocation Loc, bool DirectInit, Expr *Init)
Create an initialization from an initializer (which, for direct initialization from a parenthesized l...
Definition: Initialization.h:697
clang::isGenericLambdaCallOperatorSpecialization
bool isGenericLambdaCallOperatorSpecialization(const CXXMethodDecl *MD)
Definition: ASTLambda.h:38
AllowOverloadingOfFunction
static bool AllowOverloadingOfFunction(const LookupResult &Previous, ASTContext &Context, const FunctionDecl *New)
Determine whether overloading is allowed for a new function declaration considering prior declaration...
Definition: SemaDecl.cpp:1471
isClassCompatTagKind
static bool isClassCompatTagKind(TagTypeKind Tag)
Determine if tag kind is a class-key compatible with class for redeclaration (class,...
Definition: SemaDecl.cpp:15609
clang::Sema::MergeIntelFPGAMaxReplicatesAttr
IntelFPGAMaxReplicatesAttr * MergeIntelFPGAMaxReplicatesAttr(Decl *D, const IntelFPGAMaxReplicatesAttr &A)
clang::SourceManager::getFilename
StringRef getFilename(SourceLocation SpellingLoc) const
Return the filename of the file containing a SourceLocation.
Definition: SourceManager.cpp:1015
clang::DeclContext::removeDecl
void removeDecl(Decl *D)
Removes a declaration from this context.
Definition: DeclBase.cpp:1494
clang::Sema::RebuildNestedNameSpecifierInCurrentInstantiation
bool RebuildNestedNameSpecifierInCurrentInstantiation(CXXScopeSpec &SS)
Definition: SemaTemplate.cpp:10838
IsDisallowedCopyOrAssign
static bool IsDisallowedCopyOrAssign(const CXXMethodDecl *D)
Check for this common pattern:
Definition: SemaDecl.cpp:1722
clang::Type::isOpenCLSpecificType
bool isOpenCLSpecificType() const
Definition: Type.h:7017
clang::RecordDecl::setHasNonTrivialToPrimitiveCopyCUnion
void setHasNonTrivialToPrimitiveCopyCUnion(bool V)
Definition: Decl.h:4028
clang::FunctionDecl::setRangeEnd
void setRangeEnd(SourceLocation E)
Definition: Decl.h:2057
clang::FunctionDecl::hasWrittenPrototype
bool hasWrittenPrototype() const
Whether this function has a written prototype.
Definition: Decl.h:2261
clang::CXXConstructorDecl
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2421
clang::ASTContext::getTypeDeclType
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1566
clang::RecordDecl::hasVolatileMember
bool hasVolatileMember() const
Definition: Decl.h:3969
clang::CXXMethodDecl::isCopyAssignmentOperator
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition: DeclCXX.cpp:2360
clang::QualType::hasNonTrivialToPrimitiveCopyCUnion
bool hasNonTrivialToPrimitiveCopyCUnion() const
Check if this is or contains a C union that is non-trivial to copy, which is a union that has a membe...
Definition: Type.h:6644
clang::TypoCorrection::begin
decl_iterator begin()
Definition: TypoCorrection.h:232
clang::VarDecl::getSourceRange
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:2090
clang::Decl::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclBase.h:416
clang::Decl::isUnavailable
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition: DeclBase.h:702
clang::TypoCorrection::const_decl_iterator
SmallVectorImpl< NamedDecl * >::const_iterator const_decl_iterator
Definition: TypoCorrection.h:238
clang::TypoCorrection::decl_iterator
SmallVectorImpl< NamedDecl * >::iterator decl_iterator
Definition: TypoCorrection.h:230
clang::ASTContext::mergeTypes
QualType mergeTypes(QualType, QualType, bool OfBlockPointer=false, bool Unqualified=false, bool BlockReturnType=false)
Definition: ASTContext.cpp:10205
clang::Sema::DiagnoseUnusedNestedTypedefs
void DiagnoseUnusedNestedTypedefs(const RecordDecl *D)
Definition: SemaDecl.cpp:1961
mergeDeclAttribute
static bool mergeDeclAttribute(Sema &S, NamedDecl *D, const InheritableAttr *Attr, Sema::AvailabilityMergeKind AMK)
Definition: SemaDecl.cpp:2693
getTagInjectionScope
static Scope * getTagInjectionScope(Scope *S, const LangOptions &LangOpts)
Find the Scope in which a tag is implicitly declared if we see an elaborated type specifier in the sp...
Definition: SemaDecl.cpp:9184
clang::AttributePool::getFactory
AttributeFactory & getFactory() const
Definition: ParsedAttr.h:815
TypeLocBuilder.h
clang::FunctionDecl::getNumParams
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3402
clang::Type::isBlockPointerType
bool isBlockPointerType() const
Definition: Type.h:6758
clang::ASTContext::hasDirectOwnershipQualifier
bool hasDirectOwnershipQualifier(QualType Ty) const
Return true if the type has been explicitly qualified with ObjC ownership.
Definition: ASTContext.cpp:9322
clang::VarDecl::isFileVarDecl
bool isFileVarDecl() const
Returns true for file scoped variable declaration.
Definition: Decl.h:1258
clang::NestedNameSpecifier::Super
@ Super
Microsoft's '__super' specifier, stored as a CXXRecordDecl* of the class it appeared in.
Definition: NestedNameSpecifier.h:101
clang::DeclSpec::getRestrictSpecLoc
SourceLocation getRestrictSpecLoc() const
Definition: DeclSpec.h:549
clang::DeclContext::decls
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2127
clang::RecordDecl::setArgPassingRestrictions
void setArgPassingRestrictions(ArgPassingKind Kind)
Definition: Decl.h:4043
clang::Decl::setDeclContext
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:327
clang::VarDecl::getTLSKind
TLSKind getTLSKind() const
Definition: Decl.cpp:2068
clang::FPOptions::isFPConstrained
bool isFPConstrained() const
Definition: LangOptions.h:610
clang::ParsedTargetAttr::Architecture
StringRef Architecture
Definition: Attr.h:356
clang::interp::APInt
llvm::APInt APInt
Definition: Integral.h:27
clang::UnqualifiedId::TemplateId
TemplateIdAnnotation * TemplateId
When Kind == IK_TemplateId or IK_ConstructorTemplateId, the template-id annotation that contains the ...
Definition: DeclSpec.h:1002
clang::Sema::ForVisibleRedeclaration
@ ForVisibleRedeclaration
The lookup results will be used for redeclaration of a name, if an entity by that name already exists...
Definition: Sema.h:4361
clang::RecordDecl::setHasFlexibleArrayMember
void setHasFlexibleArrayMember(bool V)
Definition: Decl.h:3943
clang::Sema::MergeSYCLIntelMaxGlobalWorkDimAttr
SYCLIntelMaxGlobalWorkDimAttr * MergeSYCLIntelMaxGlobalWorkDimAttr(Decl *D, const SYCLIntelMaxGlobalWorkDimAttr &A)
clang::DeclContext::specific_decl_iterator
specific_decl_iterator - Iterates over a subrange of declarations stored in a DeclContext,...
Definition: DeclBase.h:2147
clang::Sema::TUKind
const TranslationUnitKind TUKind
The kind of translation unit we are processing.
Definition: Sema.h:1593
clang::MultiVersionKind::CPUDispatch
@ CPUDispatch
clang::Sema::deduceOpenCLAddressSpace
void deduceOpenCLAddressSpace(ValueDecl *decl)
Definition: SemaDecl.cpp:6584
clang::TemplateIdAnnotation
Information about a template-id annotation token.
Definition: ParsedTemplate.h:149
clang::TypeSourceInfo::getType
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:6484
clang::ASTContext::UnsignedShortTy
CanQualType UnsignedShortTy
Definition: ASTContext.h:1102
clang::UnqualifiedIdKind::IK_OperatorFunctionId
@ IK_OperatorFunctionId
An overloaded operator name, e.g., operator+.
clang::ASTContext::GetGVALinkageForFunction
GVALinkage GetGVALinkageForFunction(const FunctionDecl *FD) const
Definition: ASTContext.cpp:11389
clang::Sema::ActOnTypedefNameDecl
NamedDecl * ActOnTypedefNameDecl(Scope *S, DeclContext *DC, TypedefNameDecl *D, LookupResult &Previous, bool &Redeclaration)
ActOnTypedefNameDecl - Perform semantic checking for a declaration which declares a typedef-name,...
Definition: SemaDecl.cpp:6438
clang::Sema::AvailabilityMergeKind
AvailabilityMergeKind
Describes the kind of merge to perform for availability attributes (including "deprecated",...
Definition: Sema.h:3636
clang::EnumConstantDecl::Create
static EnumConstantDecl * Create(ASTContext &C, EnumDecl *DC, SourceLocation L, IdentifierInfo *Id, QualType T, Expr *E, const llvm::APSInt &V)
Definition: Decl.cpp:4970
clang::AttributeCommonInfo::Kind
Kind
Definition: AttributeCommonInfo.h:52
clang::Sema::CFT_Host
@ CFT_Host
Definition: Sema.h:12803
clang::ASTContext::ResetObjCLayout
void ResetObjCLayout(const ObjCContainerDecl *CD)
Definition: ASTContext.cpp:10613
clang::Sema::mergeDLLImportAttr
DLLImportAttr * mergeDLLImportAttr(Decl *D, const AttributeCommonInfo &CI)
clang::TargetInfo::isValidGCCRegisterName
virtual bool isValidGCCRegisterName(StringRef Name) const
Returns whether the passed in string is a valid register name according to GCC.
Definition: TargetInfo.cpp:538
clang::Sema::CUDAFunctionTarget
CUDAFunctionTarget
Definition: Sema.h:12800
clang::ObjCIvarDecl::None
@ None
Definition: DeclObjC.h:1928
clang::Sema::CheckRedeclarationExported
bool CheckRedeclarationExported(NamedDecl *New, NamedDecl *Old)
Definition: SemaDecl.cpp:1656
type
clang::CXXMethodDecl::isStatic
bool isStatic() const
Definition: DeclCXX.cpp:2092
clang::LabelDecl::isResolvedMSAsmLabel
bool isResolvedMSAsmLabel() const
Definition: Decl.h:530
clang::CXXFinalOverriderMap
A mapping from each virtual member function to its set of final overriders.
Definition: CXXInheritance.h:357
clang::Sema::MergeSYCLIntelNoGlobalWorkOffsetAttr
SYCLIntelNoGlobalWorkOffsetAttr * MergeSYCLIntelNoGlobalWorkOffsetAttr(Decl *D, const SYCLIntelNoGlobalWorkOffsetAttr &A)
clang::AttributedType
An attributed type is a type to which a type attribute has been applied.
Definition: Type.h:4704
clang::QualType::hasNonTrivialToPrimitiveDefaultInitializeCUnion
bool hasNonTrivialToPrimitiveDefaultInitializeCUnion() const
Check if this is or contains a C union that is non-trivial to default-initialize, which is a union th...
Definition: Type.h:6632
clang::VarDecl::setConstexpr
void setConstexpr(bool IC)
Definition: Decl.h:1481
clang::Sema::LookupLocalFriendName
@ LookupLocalFriendName
Look up a friend of a local class.
Definition: Sema.h:4340
clang::FunctionDecl::getReturnType
QualType getReturnType() const
Definition: Decl.h:2541
clang::LangOptions::getOpenCLCompatibleVersion
unsigned getOpenCLCompatibleVersion() const
Return the OpenCL version that kernel language is compatible with.
Definition: LangOptions.cpp:55
clang::CXXScopeSpec::Adopt
void Adopt(NestedNameSpecifierLoc Other)
Adopt an existing nested-name-specifier (with source-range information).
Definition: DeclSpec.cpp:131
clang::DeclaratorDecl::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:779
clang::ParmVarDecl::getOriginalType
QualType getOriginalType() const
Definition: Decl.cpp:2779
clang::Decl::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:420
clang::Sema::MergeSYCLIntelSchedulerTargetFmaxMhzAttr
SYCLIntelSchedulerTargetFmaxMhzAttr * MergeSYCLIntelSchedulerTargetFmaxMhzAttr(Decl *D, const SYCLIntelSchedulerTargetFmaxMhzAttr &A)
isMainFileLoc
static bool isMainFileLoc(const Sema &S, SourceLocation Loc)
Definition: SemaDecl.cpp:1760
copyAttrFromTypedefToDecl
static void copyAttrFromTypedefToDecl(Sema &S, Decl *D, const TypedefType *TT)
Definition: SemaDecl.cpp:7072
clang::FunctionDecl::TK_MemberSpecialization
@ TK_MemberSpecialization
Definition: Decl.h:1870
Error
llvm::Error Error
Definition: ByteCodeEmitter.cpp:20
clang::DeclSpec::TST_enum
static const TST TST_enum
Definition: DeclSpec.h:283
clang::LinkageSpecDecl
Represents a linkage specification.
Definition: DeclCXX.h:2817
clang::TagDecl::setFreeStanding
void setFreeStanding(bool isFreeStanding=true)
True if this tag is free standing, e.g. "struct foo;".
Definition: Decl.h:3475
clang::ASTContext::GE_Missing_setjmp
@ GE_Missing_setjmp
Missing a type from <setjmp.h>
Definition: ASTContext.h:2204
clang::SourceRange
A trivial tuple used to represent a source range.
Definition: SourceLocation.h:210
clang::VariableArrayTypeLoc
Definition: TypeLoc.h:1589
string
string(SUBSTRING ${CMAKE_CURRENT_BINARY_DIR} 0 ${PATH_LIB_START} PATH_HEAD) string(SUBSTRING $
Definition: CMakeLists.txt:22
clang::LookupResult::end
iterator end() const
Definition: Lookup.h:336
clang::DeclContext
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1355
getTagInjectionContext
static DeclContext * getTagInjectionContext(DeclContext *DC)
Find the DeclContext in which a tag is implicitly declared if we see an elaborated type specifier in ...
Definition: SemaDecl.cpp:9175
Ret
static bool Ret(InterpState &S, CodePtr &PC, APValue &Result)
Definition: Interp.cpp:34
clang::PointerTypeLoc
Wrapper for source info for pointers.
Definition: TypeLoc.h:1258
clang::DefaultInitializedTypeVisitor::visit
RetTy visit(QualType FT, Ts &&... Args)
Definition: NonTrivialTypeVisitor.h:51
clang::Sema::mergeMinSizeAttr
MinSizeAttr * mergeMinSizeAttr(Decl *D, const AttributeCommonInfo &CI)
clang::FunctionDecl::TK_FunctionTemplate
@ TK_FunctionTemplate
Definition: Decl.h:1867
clang::ASTContext::getDependentNameType
QualType getDependentNameType(ElaboratedTypeKeyword Keyword, NestedNameSpecifier *NNS, const IdentifierInfo *Name, QualType Canon=QualType()) const
Definition: ASTContext.cpp:5023
clang::ObjCSubstitutionContext::Parameter
@ Parameter
The parameter type of a method or function.
clang::Type::isVoidPointerType
bool isVoidPointerType() const
Definition: Type.cpp:589
clang::ASTContext::GetBuiltinType
QualType GetBuiltinType(unsigned ID, GetBuiltinTypeError &Error, unsigned *IntegerConstantArgs=nullptr) const
Return the type for the specified builtin.
Definition: ASTContext.cpp:11206
clang::CXXConversionDecl
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2751
clang::TST_interface
@ TST_interface
Definition: Specifiers.h:80
clang::Sema::ActOnEnumConstant
Decl * ActOnEnumConstant(Scope *S, Decl *EnumDecl, Decl *LastEnumConstant, SourceLocation IdLoc, IdentifierInfo *Id, const ParsedAttributesView &Attrs, SourceLocation EqualLoc, Expr *Val)
Definition: SemaDecl.cpp:18265
clang::Decl::hasAttr
bool hasAttr() const
Definition: DeclBase.h:541
clang::VarDecl::hasGlobalStorage
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition: Decl.h:1142
clang::LookupResult::isSingleResult
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:308
SetNestedNameSpecifier
static void SetNestedNameSpecifier(Sema &S, DeclaratorDecl *DD, Declarator &D)
Definition: SemaDecl.cpp:6534
clang::Preprocessor::getLastMacroWithSpelling
StringRef getLastMacroWithSpelling(SourceLocation Loc, ArrayRef< TokenValue > Tokens) const
Return the name of the macro defined before Loc that has spelling Tokens.
Definition: Preprocessor.cpp:354
clang::TypoCorrection
Simple class containing the result of Sema::CorrectTypo.
Definition: TypoCorrection.h:42
clang::ParenTypeLoc::setLParenLoc
void setLParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1157
clang::Sema::MergeIntelFPGANumBanksAttr
IntelFPGANumBanksAttr * MergeIntelFPGANumBanksAttr(Decl *D, const IntelFPGANumBanksAttr &A)
clang::Sema::AMK_Override
@ AMK_Override
Merge availability attributes for an override, which requires an exact match or a weakening of constr...
Definition: Sema.h:3644
clang::FixItHint::CreateInsertion
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:97
clang::ReservedIdentifierStatus::NotReserved
@ NotReserved
clang::DeclaratorChunk::Mem
MemberPointerTypeInfo Mem
Definition: DeclSpec.h:1554
clang::TypoCorrection::getCorrectionSpecifier
NestedNameSpecifier * getCorrectionSpecifier() const
Gets the NestedNameSpecifier needed to use the typo correction.
Definition: TypoCorrection.h:91
clang::TTK_Enum
@ TTK_Enum
The "enum" keyword.
Definition: Type.h:5400
clang::Decl::getParentFunctionOrMethod
const DeclContext * getParentFunctionOrMethod() const
If this decl is defined inside a function/method/block it returns the corresponding DeclContext,...
Definition: DeclBase.cpp:286
clang::ObjCImplementationDecl
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2545
clang::Sema::getASTContext
ASTContext & getASTContext() const
Definition: Sema.h:1781
clang::DeclSpec::getExplicitSpecLoc
SourceLocation getExplicitSpecLoc() const
Definition: DeclSpec.h:584
clang::VarDecl::getCanonicalDecl
VarDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:2158
clang::DecompositionDecl::Create
static DecompositionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation LSquareLoc, QualType T, TypeSourceInfo *TInfo, StorageClass S, ArrayRef< BindingDecl * > Bindings)
Definition: DeclCXX.cpp:3214
clang::EnumDecl::enumerators
enumerator_range enumerators() const
Definition: Decl.h:3745
clang::NestedNameSpecifier::isDependent
bool isDependent() const
Whether this nested name specifier refers to a dependent type or not.
Definition: NestedNameSpecifier.cpp:234
clang::Decl::isTemplateParameter
bool isTemplateParameter() const
isTemplateParameter - Determines whether this declaration is a template parameter.
Definition: DeclBase.h:2552
clang::QualType::isConstQualified
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:6561
clang::Decl::getAsFunction
FunctionDecl * getAsFunction() LLVM_READONLY
Returns the function itself, or the templated function if this is a function template.
Definition: DeclBase.cpp:218
clang::Declarator::getNumTypeObjects
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2236
clang::Sema::SourceMgr
SourceManager & SourceMgr
Definition: Sema.h:590
clang::FunctionDecl::isConstexpr
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2283
clang::Sema::AddKnownFunctionAttributes
void AddKnownFunctionAttributes(FunctionDecl *FD)
Adds any function attributes that we know a priori based on the declaration of this function.
Definition: SemaDecl.cpp:15314
getNoteDiagForInvalidRedeclaration
static std::pair< diag::kind, SourceLocation > getNoteDiagForInvalidRedeclaration(const T *Old, const T *New)
Definition: SemaDecl.cpp:3264
clang::DeclSpec::getExplicitSpecRange
SourceRange getExplicitSpecRange() const
Definition: DeclSpec.h:585
Used
@ Used
Definition: ObjCUnusedIVarsChecker.cpp:29
clang::AttributedType::isCallingConv
bool isCallingConv() const
Definition: Type.cpp:3597
Diag
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
Definition: LiteralSupport.cpp:78
clang::Decl::isOutOfLine
virtual bool isOutOfLine() const
Determine whether this declaration is declared out of line (outside its semantic context).
Definition: Decl.cpp:99
clang::QualifierCollector::apply
QualType apply(const ASTContext &Context, QualType QT) const
Apply the collected qualifiers to the given type.
Definition: Type.cpp:3736
clang::LookupResult::FoundOverloaded
@ FoundOverloaded
Name lookup found a set of overloaded functions that met the criteria.
Definition: Lookup.h:63
clang::Sema::CheckVariableDeclarationType
void CheckVariableDeclarationType(VarDecl *NewVD)
Definition: SemaDecl.cpp:8138
clang::SourceManager::isInMainFile
bool isInMainFile(SourceLocation Loc) const
Returns whether the PresumedLoc for a given SourceLocation is in the main file.
Definition: SourceManager.cpp:1591
clang::LookupResult::Filter::next
NamedDecl * next()
Definition: Lookup.h:643
getNonCLikeKindForAnonymousStruct
static NonCLikeKind getNonCLikeKindForAnonymousStruct(const CXXRecordDecl *RD)
Determine whether a class is C-like, according to the rules of C++ [dcl.typedef] for anonymous classe...
Definition: SemaDecl.cpp:4634
clang::Sema::isMicrosoftMissingTypename
bool isMicrosoftMissingTypename(const CXXScopeSpec *SS, Scope *S)
isMicrosoftMissingTypename - In Microsoft mode, within class scope, if a CXXScopeSpec's type is equal...
Definition: SemaDecl.cpp:664
clang::FunctionDecl::isDeleted
bool isDeleted() const
Whether this function has been deleted.
Definition: Decl.h:2338
clang::Sema::checkNonTrivialCUnionInInitializer
void checkNonTrivialCUnionInInitializer(const Expr *Init, SourceLocation Loc)
Emit diagnostics if the initializer or any of its explicit or implicitly-generated subexpressions req...
Definition: SemaDecl.cpp:12095
clang::VarDecl::demoteThisDefinitionToDeclaration
void demoteThisDefinitionToDeclaration()
This is a definition which should be demoted to a declaration.
Definition: Decl.h:1395
clang::DeclSpec::isInlineSpecified
bool isInlineSpecified() const
Definition: DeclSpec.h:567
clang::TargetInfo::getLongWidth
unsigned getLongWidth() const
getLongWidth/Align - Return the size of 'signed long' and 'unsigned long' for this target,...
Definition: TargetInfo.h:459
clang::DeclSpec::getAttributes
ParsedAttributes & getAttributes()
Definition: DeclSpec.h:795
clang::NamedDecl::isExternallyVisible
bool isExternallyVisible() const
Definition: Decl.h:406
clang::ObjCIvarDecl::Protected
@ Protected
Definition: DeclObjC.h:1928
clang::Qualifiers::OCL_Weak
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:178
SemaInternal.h
clang::ASTContext::setcudaConfigureCallDecl
void setcudaConfigureCallDecl(FunctionDecl *FD)
Definition: ASTContext.h:1399
clang::BindingDecl
A binding in a decomposition declaration.
Definition: DeclCXX.h:3979
clang::ASTContext::VoidTy
CanQualType VoidTy
Definition: ASTContext.h:1092
clang::DeclarationName::CXXConstructorName
@ CXXConstructorName
Definition: DeclarationName.h:204
clang::DeclSpec::SCS_static
@ SCS_static
Definition: DeclSpec.h:237
clang::sema::Capture::getVariable
VarDecl * getVariable() const
Definition: ScopeInfo.h:637
clang::sema::LambdaScopeInfo::Mutable
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:846
llvm::SmallVector
Definition: LLVM.h:38
Lookup.h
clang::IdentifierTable::get
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
Definition: IdentifierTable.h:596
TryToFixInvalidVariablyModifiedTypeSourceInfo
static TypeSourceInfo * TryToFixInvalidVariablyModifiedTypeSourceInfo(TypeSourceInfo *TInfo, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
Definition: SemaDecl.cpp:6271
clang::Declarator::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:1945
clang::RecordDecl::field_empty
bool field_empty() const
Definition: Decl.h:4113
clang::Sema::mergeAlwaysInlineAttr
AlwaysInlineAttr * mergeAlwaysInlineAttr(Decl *D, const AttributeCommonInfo &CI, const IdentifierInfo *Ident)
clang::SourceLocation
Encodes a location in the source.
Definition: SourceLocation.h:86
clang::ASTContext::getManglingNumberContext
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
Definition: ASTContext.cpp:11811
clang::ASTContext::hasSameFunctionTypeIgnoringExceptionSpec
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U)
Determine whether two function types are the same, ignoring exception specifications in cases where t...
Definition: ASTContext.cpp:3181
clang::Sema::ActOnCXXForRangeDecl
void ActOnCXXForRangeDecl(Decl *D)
Definition: SemaDecl.cpp:13170
clang::QualType::getQualifiers
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6529
clang::Sema::CodeSegStack
PragmaStack< StringLiteral * > CodeSegStack
Definition: Sema.h:870
clang::TargetCXXABI::isMicrosoft
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:138
clang::ASTContext::getIntWidth
unsigned getIntWidth(QualType T) const
Definition: ASTContext.cpp:10696
clang::Sema::ActOnObjCContainerFinishDefinition
void ActOnObjCContainerFinishDefinition()
Definition: SemaDecl.cpp:16903
clang::Sema::mergeSectionAttr
SectionAttr * mergeSectionAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
clang::VarDecl::isInitCapture
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1487
clang::DiagnosticsEngine::isIgnored
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:915
clang::Module::getFullModuleName
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:219
clang::TTK_Struct
@ TTK_Struct
The "struct" keyword.
Definition: Type.h:5388
clang::Sema::CheckMSVCRTEntryPoint
void CheckMSVCRTEntryPoint(FunctionDecl *FD)
Definition: SemaDecl.cpp:11526
clang::DeclSpec::TST_error
static const TST TST_error
Definition: DeclSpec.h:301
clang::NamedDecl
This represents a decl that may have a name.
Definition: Decl.h:247
clang::DeclContext::getPrimaryContext
DeclContext * getPrimaryContext()
getPrimaryContext - There may be many different declarations of the same entity (including forward de...
Definition: DeclBase.cpp:1241
clang::ASTContext::BuiltinInfo
Builtin::Context & BuiltinInfo
Definition: ASTContext.h:653
clang::ParenListExpr
Definition: Expr.h:5590
clang::SourceRange::getBegin
SourceLocation getBegin() const
Definition: SourceLocation.h:219
clang::DeclGroupRef::Create
static DeclGroupRef Create(ASTContext &C, Decl **Decls, unsigned NumDecls)
Definition: DeclGroup.h:68
clang::VarDecl::setInit
void setInit(Expr *I)
Definition: Decl.cpp:2355
clang::DeclaratorChunk::MemberPointer
@ MemberPointer
Definition: DeclSpec.h:1177
DeclHasAttr
static bool DeclHasAttr(const Decl *D, const Attr *A)
DeclhasAttr - returns true if decl Declaration already has the target attribute.
Definition: SemaDecl.cpp:2551
clang::Attr::getLocation
SourceLocation getLocation() const
Definition: Attr.h:91
clang::NamedDecl::isLinkageValid
bool isLinkageValid() const
True if the computed linkage is valid.
Definition: Decl.cpp:1082
clang::UnqualifiedIdKind::IK_DeductionGuideName
@ IK_DeductionGuideName
A deduction-guide name (a template-name)
clang::Sema::ActOnNameClassifiedAsDependentNonType
ExprResult ActOnNameClassifiedAsDependentNonType(const CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, bool IsAddressOfOperand)
Act on the result of classifying a name as an undeclared member of a dependent base class.
Definition: SemaDecl.cpp:1234
EvaluatedExprVisitor.h
clang::FunctionType::ExtInfo::withNoReturn
ExtInfo withNoReturn(bool noReturn) const
Definition: Type.h:3746
TargetInfo.h
clang::NamedDecl::getUnderlyingDecl
NamedDecl * getUnderlyingDecl()
Looks through UsingDecls and ObjCCompatibleAliasDecls for the underlying named decl.
Definition: Decl.h:458
clang::MultiVersionKind::Target
@ Target
clang::ASTContext::setFILEDecl
void setFILEDecl(TypeDecl *FILEDecl)
Set the type for the C FILE type.
Definition: ASTContext.h:1920
checkUsingShadowRedecl
static bool checkUsingShadowRedecl(Sema &S, UsingShadowDecl *OldS, ExpectedDecl *New)
Check whether a redeclaration of an entity introduced by a using-declaration is valid,...
Definition: SemaDecl.cpp:3318
clang::AttributedTypeLoc::getAttrAs
const T * getAttrAs()
Definition: TypeLoc.h:889
clang::Sema::shouldSkipAnonEnumBody
SkipBodyInfo shouldSkipAnonEnumBody(Scope *S, IdentifierInfo *II, SourceLocation IILoc)
Determine whether the body of an anonymous enumeration should be skipped.
Definition: SemaDecl.cpp:18239
clang::ASTContext::getAdjustedParameterType
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
Definition: ASTContext.cpp:6736
clang::Sema::NonTrivialCUnionContext
NonTrivialCUnionContext
Definition: Sema.h:3088
clang::CastExpr::getSubExpr
Expr * getSubExpr()
Definition: Expr.h:3582
CXXInheritance.h
clang::ParsedTargetAttr
Contains information gathered from parsing the contents of TargetAttr.
Definition: Attr.h:354
clang::ASTContext::GE_Missing_ucontext
@ GE_Missing_ucontext
Missing a type from <ucontext.h>
Definition: ASTContext.h:2207
clang::DeclSpec::getRepAsExpr
Expr * getRepAsExpr() const
Definition: DeclSpec.h:494
clang::ASTContext::DeclarationNames
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:655
clang::RecordDecl::setHasVolatileMember
void setHasVolatileMember(bool val)
Definition: Decl.h:3971
clang::Stmt::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition: Stmt.cpp:324
clang::CXXRecordDecl::getDefinition
CXXRecordDecl * getDefinition() const
Definition: DeclCXX.h:542
clang::FunctionDecl::getCanonicalDecl
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3327
clang::MultiExprArg
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:272
clang::VarDecl::TLS_Static
@ TLS_Static
TLS with a known-constant initializer.
Definition: Decl.h:895
clang::DeclSpec::SCS_auto
@ SCS_auto
Definition: DeclSpec.h:238
clang::QualType
A (possibly-)qualified type.
Definition: Type.h:675
clang::TypeDecl::getTypeForDecl
const Type * getTypeForDecl() const
Definition: Decl.h:3166
clang::EnumDecl::isFixed
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:3821
clang::Sema::MergeIntelFPGAForcePow2DepthAttr
IntelFPGAForcePow2DepthAttr * MergeIntelFPGAForcePow2DepthAttr(Decl *D, const IntelFPGAForcePow2DepthAttr &A)
clang::Type::isScalarType
bool isScalarType() const
Definition: Type.h:7144
clang::TemplateName::getAsTemplateDecl
TemplateDecl * getAsTemplateDecl() const
Retrieve the underlying template declaration that this template name refers to, if known.
Definition: TemplateName.cpp:101
findDefaultInitializer
static SourceLocation findDefaultInitializer(const CXXRecordDecl *Record)
Definition: SemaDecl.cpp:5171
clang::CXXRecordDecl::hasNonTrivialCopyAssignment
bool hasNonTrivialCopyAssignment() const
Determine whether this class has a non-trivial copy assignment operator (C++ [class....
Definition: DeclCXX.h:1289
clang::FunctionDecl::getParamDecl
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2510
clang::FunctionDefinitionKind::Deleted
@ Deleted
clang::Type::isFunctionNoProtoType
bool isFunctionNoProtoType() const
Definition: Type.h:2020
clang::Redeclarable::redecls_end
redecl_iterator redecls_end() const
Definition: Redeclarable.h:303
clang::Sema::mergeVisibilityAttr
VisibilityAttr * mergeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, VisibilityAttr::VisibilityType Vis)
clang::Declarator::getIdentifier
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2188
clang::EST_None
@ EST_None
no exception specification
Definition: ExceptionSpecificationType.h:21
clang::TypedefNameDecl::getTypeSourceInfo
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3234
clang::NestedNameSpecifier
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
Definition: NestedNameSpecifier.h:50
clang::Sema::ActOnReenterFunctionContext
void ActOnReenterFunctionContext(Scope *S, Decl *D)
Push the parameters of D, which must be a function, into scope.
Definition: SemaDecl.cpp:1431
clang::Sema::PragmaStack
Definition: Sema.h:767
clang::Sema::AddOverriddenMethods
bool AddOverriddenMethods(CXXRecordDecl *DC, CXXMethodDecl *MD)
AddOverriddenMethods - See if a method overrides any in the base classes, and if so,...
Definition: SemaDecl.cpp:8415
clang::tooling::Filter
llvm::cl::opt< std::string > Filter
clang::Sema::MergeSYCLIntelFPGAMaxConcurrencyAttr
SYCLIntelFPGAMaxConcurrencyAttr * MergeSYCLIntelFPGAMaxConcurrencyAttr(Decl *D, const SYCLIntelFPGAMaxConcurrencyAttr &A)
clang::getDLLAttr
InheritableAttr * getDLLAttr(Decl *D)
Return a DLL attribute from the declaration.
Definition: SemaInternal.h:54
clang::NamedDecl::hasLinkage
bool hasLinkage() const
Determine whether this declaration has linkage.
Definition: Decl.cpp:1844
clang::VarDecl::getInitializingDeclaration
VarDecl * getInitializingDeclaration()
Get the initializing declaration of this variable, if any.
Definition: Decl.cpp:2324
clang::ClassScopeFunctionSpecializationDecl
Declaration of a function specialization at template class scope.
Definition: DeclTemplate.h:2604
clang::TST_struct
@ TST_struct
Definition: Specifiers.h:78
clang::FunctionDecl::willHaveBody
bool willHaveBody() const
True if this function will eventually have a body, once it's fully parsed.
Definition: Decl.h:2431
clang::UnresolvedSetIterator
The iterator over UnresolvedSets.
Definition: UnresolvedSet.h:32
clang::Sema::mergeDLLExportAttr
DLLExportAttr * mergeDLLExportAttr(Decl *D, const AttributeCommonInfo &CI)
clang::QualType::getCanonicalType
QualType getCanonicalType() const
Definition: Type.h:6541
clang::FieldDecl
Represents a member of a struct/union/class.
Definition: Decl.h:2839
clang::EnumDecl::getIntegerTypeRange
SourceRange getIntegerTypeRange() const LLVM_READONLY
Retrieve the source range that covers the underlying type if specified.
Definition: Decl.cpp:4460
ValidDuplicateEnum
static bool ValidDuplicateEnum(EnumConstantDecl *ECD, EnumDecl *Enum)
Definition: SemaDecl.cpp:18343
clang::sema::FunctionScopeInfo::NeedsScopeChecking
bool NeedsScopeChecking() const
Definition: ScopeInfo.h:464
clang::Sema::FilterLookupForScope
void FilterLookupForScope(LookupResult &R, DeclContext *Ctx, Scope *S, bool ConsiderLinkage, bool AllowInlineNamespace)
Filters out lookup results that don't fall within the given scope as determined by isDeclInScope.
Definition: SemaDecl.cpp:1578
clang::TagDecl::setBraceRange
void setBraceRange(SourceRange R)
Definition: Decl.h:3414
clang::Type::isFloatingType
bool isFloatingType() const
Definition: Type.cpp:2122
clang::VarTemplateDecl::getInstantiatedFromMemberTemplate
VarTemplateDecl * getInstantiatedFromMemberTemplate() const
Definition: DeclTemplate.h:3181
clang::DiagnosticsEngine
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
clang::TagDecl::setQualifierInfo
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:4388
clang::DeclaratorChunk::Fun
FunctionTypeInfo Fun
Definition: DeclSpec.h:1552
clang::FunctionType::ExtInfo::getNoCallerSavedRegs
bool getNoCallerSavedRegs() const
Definition: Type.h:3723
clang::LookupResult
Represents the results of name lookup.
Definition: Lookup.h:46
clang::ASTContext::getBaseElementType
QualType getBaseElementType(const ArrayType *VAT) const
Return the innermost element type of an array type.
Definition: ASTContext.cpp:6789
clang::PipeType
PipeType - OpenCL20.
Definition: Type.h:6350
clang::DeclListNode::iterator
Definition: DeclBase.h:1252
clang::TargetInfo::getCXXABI
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1233
clang::FunctionProtoType::hasExceptionSpec
bool hasExceptionSpec() const
Return whether this function has any kind of exception spec.
Definition: Type.h:4141
clang::ParmVarDecl
Represents a parameter to a function.
Definition: Decl.h:1664
clang::TypoCorrection::setCorrectionDecl
void setCorrectionDecl(NamedDecl *CDecl)
Clears the list of NamedDecls before adding the new one.
Definition: TypoCorrection.h:166
clang::Sema::Diag
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1960
checkIsValidOpenCLKernelParameter
static void checkIsValidOpenCLKernelParameter(Sema &S, Declarator &D, ParmVarDecl *Param, llvm::SmallPtrSetImpl< const Type * > &ValidTypes)
Definition: SemaDecl.cpp:8997
clang::Scope::isCompoundStmtScope
bool isCompoundStmtScope() const
Determine whether this scope is a compound statement scope.
Definition: Scope.h:482
clang::Redeclarable::getFirstDecl
decl_type * getFirstDecl()
Return the first declaration of this declaration or itself if this is the only declaration.
Definition: Redeclarable.h:216
clang::TargetInfo
Exposes information about the current target.
Definition: TargetInfo.h:186
DeclCXX.h
clang::DeclSpec::hasAutoTypeSpec
bool hasAutoTypeSpec() const
Definition: DeclSpec.h:526
int
__device__ int
Definition: __clang_hip_libdevice_declares.h:63
clang::DeclarationNameTable::getCXXConversionFunctionName
DeclarationName getCXXConversionFunctionName(CanQualType Ty)
Returns the name of a C++ conversion function for the given Type.
Definition: DeclarationName.cpp:343
clang::ASTContext::getFunctionType
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1544
clang::FunctionType::ExtInfo::withProducesResult
ExtInfo withProducesResult(bool producesResult) const
Definition: Type.h:3753
clang::Decl::isUsed
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition: DeclBase.cpp:443
clang::DeclarationNameInfo::setCXXOperatorNameRange
void setCXXOperatorNameRange(SourceRange R)
setCXXOperatorNameRange - Sets the range of the operator name (without the operator keyword).
Definition: DeclarationName.h:822
clang::UnqualifiedIdKind::IK_Identifier
@ IK_Identifier
An identifier.
clang::Type::getContainedDeducedType
DeducedType * getContainedDeducedType() const
Get the DeducedType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.cpp:1889
clang::CXXMethodDecl::getCanonicalDecl
CXXMethodDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:2053
CheckMultiVersionAdditionalDecl
static bool CheckMultiVersionAdditionalDecl(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, MultiVersionKind NewMVKind, const TargetAttr *NewTA, const CPUDispatchAttr *NewCPUDisp, const CPUSpecificAttr *NewCPUSpec, const TargetClonesAttr *NewClones, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a new function declaration being added to an existing multiversioned declaratio...
Definition: SemaDecl.cpp:10756
clang::Sema::getTypeName
ParsedType getTypeName(const IdentifierInfo &II, SourceLocation NameLoc, Scope *S, CXXScopeSpec *SS=nullptr, bool isClassName=false, bool HasTrailingDot=false, ParsedType ObjectType=nullptr, bool IsCtorOrDtorName=false, bool WantNontrivialTypeSourceInfo=false, bool IsClassTemplateDeductionContext=true, IdentifierInfo **CorrectedII=nullptr)
If the identifier refers to a type name within this scope, return the declaration of that type.
Definition: SemaDecl.cpp:285
clang::LookupResult::NotFoundInCurrentInstantiation
@ NotFoundInCurrentInstantiation
No entity found met the criteria within the current instantiation,, but there were dependent base cla...
Definition: Lookup.h:55
mergeTypeWithPrevious
static bool mergeTypeWithPrevious(Sema &S, VarDecl *NewVD, VarDecl *OldVD, LookupResult &Previous)
Definition: SemaDecl.cpp:4210
TryToFixInvalidVariablyModifiedType
static QualType TryToFixInvalidVariablyModifiedType(QualType T, ASTContext &Context, bool &SizeIsNegative, llvm::APSInt &Oversized)
Helper method to turn variable array types into constant array types in certain situations which woul...
Definition: SemaDecl.cpp:6155
clang::BinaryConditionalOperator::getCond
Expr * getCond() const
getCond - Return the condition expression; this is defined in terms of the opaque value.
Definition: Expr.h:4303
clang::VarTemplateDecl::getTemplatedDecl
VarDecl * getTemplatedDecl() const
Get the underlying variable declarations of the template.
Definition: DeclTemplate.h:3124
clang::Sema::DiagnoseSizeOfParametersAndReturnValue
void DiagnoseSizeOfParametersAndReturnValue(ArrayRef< ParmVarDecl * > Parameters, QualType ReturnTy, NamedDecl *D)
Diagnose whether the size of parameters or return value of a function or obj-c method definition is p...
Definition: SemaDecl.cpp:14087
clang::Sema::ActOnCXXForRangeIdentifier
StmtResult ActOnCXXForRangeIdentifier(Scope *S, SourceLocation IdentLoc, IdentifierInfo *Ident, ParsedAttributes &Attrs)
Definition: SemaDecl.cpp:13224
clang::EnumConstantDecl::getInitExpr
const Expr * getInitExpr() const
Definition: Decl.h:3073
clang::C99
@ C99
Definition: LangStandard.h:44
clang::UsingShadowDecl
Represents a shadow declaration implicitly introduced into a scope by a (resolved) using-declaration ...
Definition: DeclCXX.h:3207
clang::DeclarationName::CXXDeductionGuideName
@ CXXDeductionGuideName
Definition: DeclarationName.h:208
clang::StringLiteral::getStrTokenLoc
SourceLocation getStrTokenLoc(unsigned TokNum) const
Get one of the string literal token.
Definition: Expr.h:1914
clang::TemplateSpecializationType
Represents a type template specialization; the template must be a class template, a type alias templa...
Definition: Type.h:5181
clang::ASTContext::PSF_Execute
@ PSF_Execute
Definition: ASTContext.h:3265
clang::FunctionDecl::isOverloadedOperator
bool isOverloadedOperator() const
Whether this function declaration represents an C++ overloaded operator, e.g., "operator+".
Definition: Decl.h:2629
clang::Sema::VerifyBitField
ExprResult VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName, QualType FieldTy, bool IsMsStruct, Expr *BitWidth, bool *ZeroWidth=nullptr)
VerifyBitField - verifies that a bit field expression is an ICE and has the correct width,...
Definition: SemaDecl.cpp:16938
clang::Sema::mergeEnforceTCBLeafAttr
EnforceTCBLeafAttr * mergeEnforceTCBLeafAttr(Decl *D, const EnforceTCBLeafAttr &AL)
clang::SourceRange::isValid
bool isValid() const
Definition: SourceLocation.h:225
clang::ASTContext::PSF_Write
@ PSF_Write
Definition: ASTContext.h:3264
clang::DeclarationNameTable::getCXXDestructorName
DeclarationName getCXXDestructorName(CanQualType Ty)
Returns the name of a C++ destructor for the given Type.
Definition: DeclarationName.cpp:326
clang::RecoveryExpr
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition: Expr.h:6474
clang::Decl::setTopLevelDeclInObjCContainer
void setTopLevelDeclInObjCContainer(bool V=true)
Definition: DeclBase.h:596
clang::FunctionDecl::getTemplateSpecializationInfo
FunctionTemplateSpecializationInfo * getTemplateSpecializationInfo() const
If this function is actually a function template specialization, retrieve information about this func...
Definition: Decl.cpp:3844
RebuildDeclaratorInCurrentInstantiation
static bool RebuildDeclaratorInCurrentInstantiation(Sema &S, Declarator &D, DeclarationName Name)
NeedsRebuildingInCurrentInstantiation - Checks whether the given declarator needs to be rebuilt in th...
Definition: SemaDecl.cpp:5710
clang::TargetInfo::getCharWidth
unsigned getCharWidth() const
Definition: TargetInfo.h:441
clang::Sema::LookupQualifiedName
bool LookupQualifiedName(LookupResult &R, DeclContext *LookupCtx, bool InUnqualifiedLookup=false)
Perform qualified name lookup into a given context.
Definition: SemaLookup.cpp:2223
clang::FunctionType::getExtInfo
ExtInfo getExtInfo() const
Definition: Type.h:3836
clang::DeclSpec::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclSpec.h:506
clang::Sema::FunctionEmissionStatus::Unknown
@ Unknown
clang::Sema::tryToFixVariablyModifiedVarType
bool tryToFixVariablyModifiedVarType(TypeSourceInfo *&TInfo, QualType &T, SourceLocation Loc, unsigned FailedFoldDiagID)
Attempt to fold a variable-sized type to a constant-sized type, returning true if we were successful.
Definition: SemaDecl.cpp:6288
clang::Sema::MergeTypedefNameDecl
void MergeTypedefNameDecl(Scope *S, TypedefNameDecl *New, LookupResult &OldDecls)
MergeTypedefNameDecl - We just parsed a typedef 'New' which has the same name and scope as a previous...
Definition: SemaDecl.cpp:2378
clang::FunctionDecl::getPrimaryTemplate
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:3834
clang::FunctionDecl::hasImplicitReturnZero
bool hasImplicitReturnZero() const
Whether falling off this function implicitly returns null/zero.
Definition: Decl.h:2241
hasIdenticalPassObjectSizeAttrs
static bool hasIdenticalPassObjectSizeAttrs(const FunctionDecl *A, const FunctionDecl *B)
Definition: SemaDecl.cpp:3353
clang::TST_enum
@ TST_enum
Definition: Specifiers.h:76
clang::InitListExpr
Describes an C or C++ initializer list.
Definition: Expr.h:4844
clang::QualType::getBaseTypeIdentifier
const IdentifierInfo * getBaseTypeIdentifier() const
Retrieves a pointer to the name of the base type.
Definition: Type.cpp:73
clang::DeclSpec::SCS
SCS
storage-class-specifier
Definition: DeclSpec.h:233
clang::sema::CapturingScopeInfo::addVLATypeCapture
void addVLATypeCapture(SourceLocation Loc, const VariableArrayType *VLAType, QualType CaptureType)
Definition: ScopeInfo.h:701
clang::ParmVarDecl::getObjCDeclQualifier
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1728
clang::DeclSpec::SCS_unspecified
@ SCS_unspecified
Definition: DeclSpec.h:234
clang::Qualifiers::OCL_ExplicitNone
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:168
clang::FunctionDecl::getDeclaredReturnType
QualType getDeclaredReturnType() const
Get the declared return type, which may differ from the actual return type if the return type is dedu...
Definition: Decl.h:2558
clang::Sema::getEmissionReason
DeviceDiagnosticReason getEmissionReason(const FunctionDecl *Decl)
Definition: SemaDecl.cpp:18818
llvm::Optional< bool >
clang::CXXRecordDecl::Create
static CXXRecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, CXXRecordDecl *PrevDecl=nullptr, bool DelayTypeCreation=false)
Definition: DeclCXX.cpp:131
clang::DeclarationNameTable::getCXXDeductionGuideName
DeclarationName getCXXDeductionGuideName(TemplateDecl *TD)
Returns the name of a C++ deduction guide for the given template.
Definition: DeclarationName.cpp:295
clang::ComparisonCategoryType::First
@ First
clang::Sema::ActOnStartCXXMemberDeclarations
void ActOnStartCXXMemberDeclarations(Scope *S, Decl *TagDecl, SourceLocation FinalLoc, bool IsFinalSpelledSealed, bool IsAbstract, SourceLocation LBraceLoc)
ActOnStartCXXMemberDeclarations - Invoked when we have parsed a C++ record definition's base-specifie...
Definition: SemaDecl.cpp:16803
clang::Declarator::getFunctionDefinitionKind
FunctionDefinitionKind getFunctionDefinitionKind() const
Definition: DeclSpec.h:2580
clang::Decl::getOwningModuleForLinkage
Module * getOwningModuleForLinkage(bool IgnoreLinkage=false) const
Get the module that owns this declaration for linkage purposes.
Definition: Decl.cpp:1549
clang::RedeclarableTemplateDecl::setMemberSpecialization
void setMemberSpecialization()
Note that this member template is a specialization.
Definition: DeclTemplate.h:895
clang::RecordDecl::getDefinition
RecordDecl * getDefinition() const
Returns the RecordDecl that actually defines this struct/union/class.
Definition: Decl.h:4090
clang::DeclSpec::hasExplicitSpecifier
bool hasExplicitSpecifier() const
Definition: DeclSpec.h:581
clang::ActionResult::isUnset
bool isUnset() const
Definition: Ownership.h:167
clang::TypeLoc::getEndLoc
SourceLocation getEndLoc() const
Get the end source location.
Definition: TypeLoc.cpp:228
clang::Type::isVariableArrayType
bool isVariableArrayType() const
Definition: Type.h:6828
clang::ObjCMethodDecl::param_end
param_const_iterator param_end() const
Definition: DeclObjC.h:361
clang::Sema::notePreviousDefinition
void notePreviousDefinition(const NamedDecl *Old, SourceLocation New)
Definition: SemaDecl.cpp:4484
clang::Sema::ActOnFields
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:17564
llvm::SmallPtrSet
Definition: ASTContext.h:82
clang::Sema::NonTagKind
NonTagKind
Common ways to introduce type names without a tag for use in diagnostics.
Definition: Sema.h:3355
clang::UnaryOperator
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2215
clang::DeclSpec::TQ_volatile
@ TQ_volatile
Definition: DeclSpec.h:308
clang::TargetInfo::validateCpuSupports
virtual bool validateCpuSupports(StringRef Name) const
Definition: TargetInfo.h:1354
clang::QualType::getAsString
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1017
clang::TagType
Definition: Type.h:4625
SourceManager.h
getImplicitCodeSegAttrFromClass
static Attr * getImplicitCodeSegAttrFromClass(Sema &S, const FunctionDecl *FD)
Return a CodeSegAttr from a containing class.
Definition: SemaDecl.cpp:10271
clang::Sema::SkippedDefinitionContext
void * SkippedDefinitionContext
Definition: Sema.h:3516
clang::getLambdaAwareParentOfDeclContext
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:80
clang::ASTConsumer::AssignInheritanceModel
virtual void AssignInheritanceModel(CXXRecordDecl *RD)
Callback invoked when an MSInheritanceAttr has been attached to a CXXRecordDecl.
Definition: ASTConsumer.h:112
clang::SourceManager::getIncludeLoc
SourceLocation getIncludeLoc(FileID FID) const
Returns the include location if FID is a #include'd file otherwise it returns an invalid location.
Definition: SourceManager.h:1135
clang::FunctionDecl::setDefaulted
void setDefaulted(bool D=true)
Definition: Decl.h:2216
clang::TargetInfo::getLongLongWidth
unsigned getLongLongWidth() const
getLongLongWidth/Align - Return the size of 'signed long long' and 'unsigned long long' for this targ...
Definition: TargetInfo.h:464
clang::Type::isVoidType
bool isVoidType() const
Definition: Type.h:7057
clang::QualType::isVolatileQualified
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition: Type.h:6572
clang::DeclarationNameInfo::getCXXOperatorNameRange
SourceRange getCXXOperatorNameRange() const
getCXXOperatorNameRange - Gets the range of the operator name (without the operator keyword).
Definition: DeclarationName.h:814
clang::TagDecl::getTypedefNameForAnonDecl
TypedefNameDecl * getTypedefNameForAnonDecl() const
Definition: Decl.h:3560
clang::Qualifiers::empty
bool empty() const
Definition: Type.h:425
clang::Decl::setIsUsed
void setIsUsed()
Set whether the declaration is used, in the sense of odr-use.
Definition: DeclBase.h:572
clang::CPlusPlus14
@ CPlusPlus14
Definition: LangStandard.h:50
DeclSpec.h
clang::sema::FunctionScopeInfo::UsesFPIntrin
bool UsesFPIntrin
Whether this function uses constrained floating point intrinsics.
Definition: ScopeInfo.h:134
clang::sema::DelayedDiagnostic::makeForbiddenType
static DelayedDiagnostic makeForbiddenType(SourceLocation loc, unsigned diagnostic, QualType type, unsigned argument)
Definition: DelayedDiagnostic.h:154
clang::TSCS_thread_local
@ TSCS_thread_local
C++11 thread_local.
Definition: Specifiers.h:226
clang::Decl::getAttr
T * getAttr() const
Definition: DeclBase.h:537
clang::ArrayTypeLoc::getElementLoc
TypeLoc getElementLoc() const
Definition: TypeLoc.h:1549
clang::DeclaratorDecl::getOuterLocStart
SourceLocation getOuterLocStart() const
Return start of source range taking into account any outer template declarations.
Definition: Decl.cpp:1950
llvm::Expected
Definition: LLVM.h:41
clang::CXXScopeSpec
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:64
clang::Sema::isSimpleTypeSpecifier
bool isSimpleTypeSpecifier(tok::TokenKind Kind) const
Determine whether the token kind starts a simple-type-specifier.
Definition: SemaDecl.cpp:125
clang::Sema::IsOverload
bool IsOverload(FunctionDecl *New, FunctionDecl *Old, bool IsForUsingDecl, bool ConsiderCudaAttrs=true, bool ConsiderRequiresClauses=true)
Definition: SemaOverload.cpp:1141
clang::Sema::FunctionEmissionStatus
FunctionEmissionStatus
Status of the function emission on the CUDA/HIP/OpenMP host/device attrs.
Definition: Sema.h:4515
clang::ClassTemplatePartialSpecializationDecl
Definition: DeclTemplate.h:2075
clang::VarDecl::setPreviousDeclInSameBlockScope
void setPreviousDeclInSameBlockScope(bool Same)
Definition: Decl.h:1506
clang::OpenCLOptions::isAvailableOption
bool isAvailableOption(llvm::StringRef Ext, const LangOptions &LO) const
Definition: OpenCLOptions.cpp:32
clang::DeclSpec::TQ_unaligned
@ TQ_unaligned
Definition: DeclSpec.h:309
clang::PrintingPolicy
Describes how types, statements, expressions, and declarations should be printed.
Definition: PrettyPrinter.h:57
clang::RecordDecl::APK_CanNeverPassInRegs
@ APK_CanNeverPassInRegs
The argument of this type cannot be passed directly in registers.
Definition: Decl.h:3910
clang::TypedefNameDecl::setModedTypeSourceInfo
void setModedTypeSourceInfo(TypeSourceInfo *unmodedTSI, QualType modedTy)
Definition: Decl.h:3250
clang::Sema::GetNameFromUnqualifiedId
DeclarationNameInfo GetNameFromUnqualifiedId(const UnqualifiedId &Name)
Retrieves the declaration name from a parsed unqualified-id.
Definition: SemaDecl.cpp:5540
clang::Sema::ActOnObjCReenterContainerContext
void ActOnObjCReenterContainerContext(DeclContext *DC)
Definition: SemaDecl.cpp:16914
clang::sema::Capture
Definition: ScopeInfo.h:528
clang::DeclSpec::TQ_atomic
@ TQ_atomic
Definition: DeclSpec.h:312
clang::VarDecl::setInlineSpecified
void setInlineSpecified()
Definition: Decl.h:1467
ASTLambda.h
clang::FunctionDecl::isInlineSpecified
bool isInlineSpecified() const
Determine whether the "inline" keyword was specified for this function.
Definition: Decl.h:2595
clang::diag::Group
Group
Definition: DiagnosticCategories.h:23
clang::ASTContext::getCurrentKeyFunction
const CXXMethodDecl * getCurrentKeyFunction(const CXXRecordDecl *RD)
Get our current best idea for the key function of the given record decl, or nullptr if there isn't on...
Definition: RecordLayoutBuilder.cpp:3364
clang::DeclSpec::getConstSpecLoc
SourceLocation getConstSpecLoc() const
Definition: DeclSpec.h:548
clang::Sema::DeviceDiagnosticReason::CudaDevice
@ CudaDevice
CUDA specific diagnostics.
clang::ParsedAttributesView::hasAttribute
bool hasAttribute(ParsedAttr::Kind K) const
Definition: ParsedAttr.h:990
clang::FunctionDecl::setDeletedAsWritten
void setDeletedAsWritten(bool D=true)
Definition: Decl.h:2346
clang::DeclContext::getLexicalParent
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1888
IVDepExprResult::Array
@ Array
InjectAnonymousStructOrUnionMembers
static bool InjectAnonymousStructOrUnionMembers(Sema &SemaRef, Scope *S, DeclContext *Owner, RecordDecl *AnonRecord, AccessSpecifier AS, SmallVectorImpl< NamedDecl * > &Chaining)
InjectAnonymousStructOrUnionMembers - Inject the members of the anonymous struct or union AnonRecord ...
Definition: SemaDecl.cpp:5088
clang::InitializationSequence
Describes the sequence of initializations required to initialize a given object or reference with a s...
Definition: Initialization.h:788
clang::Sema::CheckConversionDeclarator
void CheckConversionDeclarator(Declarator &D, QualType &R, StorageClass &SC)
CheckConversionDeclarator - Called by ActOnDeclarator to check the well-formednes of the conversion f...
Definition: SemaDeclCXX.cpp:10728
clang::FunctionTemplateDecl::Create
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
Definition: DeclTemplate.cpp:351
clang::ObjCIvarDecl::Public
@ Public
Definition: DeclObjC.h:1928
clang::FunctionType
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:3561
clang::ConstantArrayTypeLoc
Definition: TypeLoc.h:1566
clang::ASTContext::getUsingType
QualType getUsingType(const UsingShadowDecl *Found, QualType Underlying) const
Definition: ASTContext.cpp:4620
clang::Declarator::isDecompositionDeclarator
bool isDecompositionDeclarator() const
Return whether this declarator is a decomposition declarator.
Definition: DeclSpec.h:2184
clang::DeclaratorContext::ForInit
@ ForInit
clang::Qualifiers::hasConst
bool hasConst() const
Definition: Type.h:264
clang::Token
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
clang::Sema::MarkUnusedFileScopedDecl
void MarkUnusedFileScopedDecl(const DeclaratorDecl *D)
If it's a file scoped decl that must warn if not used, keep track of it.
Definition: SemaDecl.cpp:1829
clang::Sema::PopDeclContext
void PopDeclContext()
Definition: SemaDecl.cpp:1312
clang::TemplateIdAnnotation::NumArgs
unsigned NumArgs
NumArgs - The number of template arguments.
Definition: ParsedTemplate.h:185
clang::TTK_Interface
@ TTK_Interface
The "__interface" keyword.
Definition: Type.h:5391
clang::Sema::mergeBTFDeclTagAttr
BTFDeclTagAttr * mergeBTFDeclTagAttr(Decl *D, const BTFDeclTagAttr &AL)
clang::Sema::DiagnoseClassNameShadow
bool DiagnoseClassNameShadow(DeclContext *DC, DeclarationNameInfo Info)
DiagnoseClassNameShadow - Implement C++ [class.mem]p13: If T is the name of a class,...
Definition: SemaDecl.cpp:5817
clang::Expr::IgnoreImpCasts
Expr * IgnoreImpCasts() LLVM_READONLY
Skip past any implicit casts which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:2928
clang::CXXRecordDecl::lookupInBases
bool lookupInBases(BaseMatchesCallback BaseMatches, CXXBasePaths &Paths, bool LookupInDependent=false) const
Look for entities within the base classes of this C++ class, transitively searching all base class su...
Definition: CXXInheritance.cpp:307
clang::DeclSpec::getSpecifierName
static const char * getSpecifierName(DeclSpec::TST T, const PrintingPolicy &Policy)
Turn a type-specifier-type into a string like "_Bool" or "union".
Definition: DeclSpec.cpp:542
SDK_Field
@ SDK_Field
Definition: SemaDecl.cpp:7771
clang::DeclarationName
The name of a declaration.
Definition: DeclarationName.h:143
End
SourceLocation End
Definition: USRLocFinder.cpp:167
clang::TypoCorrection::getCorrection
DeclarationName getCorrection() const
Gets the DeclarationName of the typo correction.
Definition: TypoCorrection.h:84
clang::ASTContext::getSourceManager
SourceManager & getSourceManager()
Definition: ASTContext.h:712
clang::ASTContext::getDeducedTemplateSpecializationType
QualType getDeducedTemplateSpecializationType(TemplateName Template, QualType DeducedType, bool IsDependent) const
C++17 deduced class template specialization type.
Definition: ASTContext.cpp:5747
clang::ASTContext::getDecayedType
QualType getDecayedType(QualType T) const
Return the uniqued reference to the decayed version of the given type.
Definition: ASTContext.cpp:3317
clang::CXXRecordDecl::bases_end
base_class_iterator bases_end()
Definition: DeclCXX.h:605
clang::Builtin::Context::isPredefinedRuntimeFunction
bool isPredefinedRuntimeFunction(unsigned ID) const
Determines whether this builtin is a predefined compiler-rt/libgcc function, such as "__clear_cache",...
Definition: Builtins.h:155
clang::RecordDecl::isInjectedClassName
bool isInjectedClassName() const
Determines whether this declaration represents the injected class name.
Definition: Decl.cpp:4605
clang::FieldDecl::isZeroLengthBitField
bool isZeroLengthBitField(const ASTContext &Ctx) const
Is this a zero-length bit-field? Such bit-fields aren't really bit-fields at all and instead act as a...
Definition: Decl.cpp:4223
clang::ASTContext::getTranslationUnitDecl
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1074
clang::VarDecl::setImplicitlyInline
void setImplicitlyInline()
Definition: Decl.h:1472
clang::QualType::PCK_VolatileTrivial
@ PCK_VolatileTrivial
The type would be trivial except that it is volatile-qualified.
Definition: Type.h:1172
clang::sema::LambdaScopeInfo::CallOperator
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:832
clang::Sema::DiagnoseUnusedButSetDecl
void DiagnoseUnusedButSetDecl(const VarDecl *VD)
If VD is set but not otherwise used, diagnose, for a parameter or a variable.
Definition: SemaDecl.cpp:2000
clang::LookupResult::begin
iterator begin() const
Definition: Lookup.h:335
clang::FunctionDecl::getLiteralIdentifier
const IdentifierInfo * getLiteralIdentifier() const
getLiteralIdentifier - The literal suffix identifier this function represents, if any.
Definition: Decl.cpp:3683
clang::LookupResult::getNameLoc
SourceLocation getNameLoc() const
Gets the location of the identifier.
Definition: Lookup.h:606
clang::ArrayType::Normal
@ Normal
Definition: Type.h:2905
clang::Sema::EnterTemplatedContext
void EnterTemplatedContext(Scope *S, DeclContext *DC)
Enter a template parameter scope, after it's been associated with a particular DeclContext.
Definition: SemaDecl.cpp:1388
clang::Decl::isReferenced
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:468
clang::Sema::ActOnPragmaWeakID
void ActOnPragmaWeakID(IdentifierInfo *WeakName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc)
ActOnPragmaWeakID - Called on well formed #pragma weak ident.
Definition: SemaDecl.cpp:18784
getCaptureLocation
static SourceLocation getCaptureLocation(const LambdaScopeInfo *LSI, const VarDecl *VD)
Return the location of the capture if the given lambda captures the given variable VD,...
Definition: SemaDecl.cpp:7794
clang::Type::isPromotableIntegerType
bool isPromotableIntegerType() const
More type predicates useful for type checking/promotion.
Definition: Type.cpp:2762
clang::DeclContextLookupResult::begin
iterator begin()
Definition: DeclBase.h:1314
clang::CXXRecordDecl::hasInClassInitializer
bool hasInClassInitializer() const
Whether this class has any in-class initializers for non-static data members (including those in anon...
Definition: DeclCXX.h:1110
clang::Decl::isLocalExternDecl
bool isLocalExternDecl()
Determine whether this is a block-scope declaration with linkage.
Definition: DeclBase.h:1100
clang::Declarator::getIdentifierLoc
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2194
clang::ObjCInterfaceDecl::known_extensions
known_extensions_range known_extensions() const
Definition: DeclObjC.h:1739
clang::EnumDecl::setIntegerType
void setIntegerType(QualType T)
Set the underlying integer type.
Definition: Decl.h:3781
clang::LambdaCaptureInitKind::DirectInit
@ DirectInit
[a(b)]
isIncompleteDeclExternC
static bool isIncompleteDeclExternC(Sema &S, const T *D)
Determine whether a variable is extern "C" prior to attaching an initializer.
Definition: SemaDecl.cpp:6886
clang::RecordDecl::setHasNonTrivialToPrimitiveDefaultInitializeCUnion
void setHasNonTrivialToPrimitiveDefaultInitializeCUnion(bool V)
Definition: Decl.h:4012
clang::DeclSpec::getTypeSpecTypeLoc
SourceLocation getTypeSpecTypeLoc() const
Definition: DeclSpec.h:514
clang::DeclaratorChunk::getFunction
static DeclaratorChunk getFunction(bool HasProto, bool IsAmbiguous, SourceLocation LParenLoc, ParamInfo *Params, unsigned NumParams, SourceLocation EllipsisLoc, SourceLocation RParenLoc, bool RefQualifierIsLvalueRef, SourceLocation RefQualifierLoc, SourceLocation MutableLoc, ExceptionSpecificationType ESpecType, SourceRange ESpecRange, ParsedType *Exceptions, SourceRange *ExceptionRanges, unsigned NumExceptions, Expr *NoexceptExpr, CachedTokens *ExceptionSpecTokens, ArrayRef< NamedDecl * > DeclsInPrototype, SourceLocation LocalRangeBegin, SourceLocation LocalRangeEnd, Declarator &TheDeclarator, TypeResult TrailingReturnType=TypeResult(), SourceLocation TrailingReturnTypeLoc=SourceLocation(), DeclSpec *MethodQualifiers=nullptr)
DeclaratorChunk::getFunction - Return a DeclaratorChunk for a function.
Definition: DeclSpec.cpp:160
clang::SourceManager
This class handles loading and caching of source files into memory.
Definition: SourceManager.h:626
clang::DependentNameTypeLoc::setElaboratedKeywordLoc
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2328
clang::CC_X86StdCall
@ CC_X86StdCall
Definition: Specifiers.h:265
clang::Scope::getParent
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:234
clang::FunctionDecl::isConsteval
bool isConsteval() const
Definition: Decl.h:2295
clang::Sema::ActOnDocumentableDecls
void ActOnDocumentableDecls(ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:13880
clang::EnumDecl
Represents an enum.
Definition: Decl.h:3612
clang::FunctionProtoType::isVariadic
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:4232
clang::OpaqueValueExpr
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1135
clang::Declarator::getTrailingRequiresClause
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition: DeclSpec.h:2473
clang::Sema::Context
ASTContext & Context
Definition: Sema.h:587
clang::DeclSpec::getExplicitSpecifier
ExplicitSpecifier getExplicitSpecifier() const
Definition: DeclSpec.h:574
clang::Type
The base class of the type hierarchy.
Definition: Type.h:1492
Preprocessor.h
clang::Sema::CheckNontrivialField
bool CheckNontrivialField(FieldDecl *FD)
Definition: SemaDecl.cpp:17340
clang::UsingShadowDecl::getTargetDecl
NamedDecl * getTargetDecl() const
Gets the underlying declaration which has been brought into the local scope.
Definition: DeclCXX.h:3271
clang::FieldDecl::Create
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition: Decl.cpp:4193
clang::Declarator::isStaticMember
bool isStaticMember()
Returns true if this declares a static member.
Definition: DeclSpec.cpp:412
clang::FunctionDecl::isInlined
bool isInlined() const
Determine whether this function should be inlined, because it is either marked "inline" or "constexpr...
Definition: Decl.h:2617
clang::FunctionDecl::hasPrototype
bool hasPrototype() const
Whether this function has a prototype, either because one was explicitly written or because it was "i...
Definition: Decl.h:2256
clang::DeclContext::getNonTransparentContext
DeclContext * getNonTransparentContext()
Definition: DeclBase.cpp:1232
clang::FunctionTemplateSpecializationInfo::getTemplate
FunctionTemplateDecl * getTemplate() const
Retrieve the template from which this function was specialized.
Definition: DeclTemplate.h:527
clang::ObjCIvarDecl::AccessControl
AccessControl
Definition: DeclObjC.h:1927
clang::ExprError
ExprResult ExprError()
Definition: Ownership.h:278
computeShadowedDeclKind
static ShadowedDeclKind computeShadowedDeclKind(const NamedDecl *ShadowedDecl, const DeclContext *OldDC)
Determine what kind of declaration we're shadowing.
Definition: SemaDecl.cpp:7778
canRedefineFunction
static bool canRedefineFunction(const FunctionDecl *FD, const LangOptions &LangOpts)
canRedefineFunction - checks if a function can be redefined.
Definition: SemaDecl.cpp:3281
clang::ConditionalOperator
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4199
clang::CXXScopeSpec::clear
void clear()
Definition: DeclSpec.h:212
clang::TypedefType
Definition: Type.h:4407
clang::Type::containsErrors
bool containsErrors() const
Whether this type is an error type.
Definition: Type.h:2177
clang::Sema::SFINAETrap
RAII class used to determine whether SFINAE has trapped any errors that occur during template argumen...
Definition: Sema.h:9523
clang::UnqualifiedId::StartLocation
SourceLocation StartLocation
The location of the first token that describes this unqualified-id, which will be the location of the...
Definition: DeclSpec.h:1008
clang::EnumDecl::isComplete
bool isComplete() const
Returns true if this can be considered a complete type.
Definition: Decl.h:3826
clang::Sema::ActOnTagFinishSkippedDefinition
void ActOnTagFinishSkippedDefinition(SkippedDefinitionContext Context)
Definition: SemaDecl.cpp:1333
DeclObjC.h
clang::Type::isAggregateType
bool isAggregateType() const
Determines whether the type is a C++ aggregate type or C aggregate or union type.
Definition: Type.cpp:2211
clang::ASTContext::getAttributedType
QualType getAttributedType(attr::Kind attrKind, QualType modifiedType, QualType equivalentType)
Definition: ASTContext.cpp:4683
clang::CXXMethodDecl::Create
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2180
clang::Type::getAsStructureType
const RecordType * getAsStructureType() const
Definition: Type.cpp:641
clang::ConstexprSpecKind::Constinit
@ Constinit
clang::CXXScopeSpec::isSet
bool isSet() const
Deprecated.
Definition: DeclSpec.h:210
clang::AS_none
@ AS_none
Definition: Specifiers.h:112
clang::LinkageSpecDecl::lang_c
@ lang_c
Definition: DeclCXX.h:2826
clang::FunctionDecl::getDefinition
FunctionDecl * getDefinition()
Get the definition for this declaration.
Definition: Decl.h:2119
clang::TypeLoc::getBeginLoc
SourceLocation getBeginLoc() const
Get the begin source location.
Definition: TypeLoc.cpp:191
clang::CPlusPlus17
@ CPlusPlus17
Definition: LangStandard.h:51
clang::FixItHint
Annotates a diagnostic with some code that should be inserted, removed, or replaced to fix the proble...
Definition: Diagnostic.h:71
clang::Sema::CheckFieldDecl
FieldDecl * CheckFieldDecl(DeclarationName Name, QualType T, TypeSourceInfo *TInfo, RecordDecl *Record, SourceLocation Loc, bool Mutable, Expr *BitfieldWidth, InClassInitStyle InitStyle, SourceLocation TSSL, AccessSpecifier AS, NamedDecl *PrevDecl, Declarator *D=nullptr)
Build a new FieldDecl and check its well-formedness.
Definition: SemaDecl.cpp:17149
clang::FunctionType::getCmseNSCallAttr
bool getCmseNSCallAttr() const
Definition: Type.h:3834
clang::ASTContext::typesAreCompatible
bool typesAreCompatible(QualType T1, QualType T2, bool CompareUnqualified=false)
Compatibility predicates used to check assignment expressions.
Definition: ASTContext.cpp:9947
clang::InheritableAttr
Definition: Attr.h:140
clang::Type::hasAutoForTrailingReturnType
bool hasAutoForTrailingReturnType() const
Determine whether this type was written with a leading 'auto' corresponding to a trailing return type...
Definition: Type.cpp:1894
clang::AttributeCommonInfo::AS_Keyword
@ AS_Keyword
__ptr16, alignas(...), etc.
Definition: AttributeCommonInfo.h:42
clang::Sema::getLangOpts
const LangOptions & getLangOpts() const
Definition: Sema.h:1774
clang::CXXConstructorDecl::Create
static CXXConstructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, ExplicitSpecifier ES, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, InheritedConstructor Inherited=InheritedConstructor(), Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2604
clang::DeclSpec::TST_underlyingType
static const TST TST_underlyingType
Definition: DeclSpec.h:293
clang::Sema::MergeCompatibleFunctionDecls
bool MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old, Scope *S, bool MergeTypeWithOld)
Completes the merge of two function declarations that are known to be compatible.
Definition: SemaDecl.cpp:4041
clang::BlockDecl::doesNotEscape
bool doesNotEscape() const
Definition: Decl.h:4330
clang::Declarator::takeAttributes
void takeAttributes(ParsedAttributes &attrs)
takeAttributes - Takes attributes from the given parsed-attributes set and add them to this declarato...
Definition: DeclSpec.h:2516
IsPartialSpecialization
Definition: SemaTemplateDeduction.cpp:2775
clang::RecordDecl::setHasObjectMember
void setHasObjectMember(bool val)
Definition: Decl.h:3967
clang::DeclSpec::SetRangeStart
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:638
clang::sema::LambdaScopeInfo::Lambda
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:829
clang::FunctionTypeLoc
Wrapper for source info for functions.
Definition: TypeLoc.h:1383
BuiltinInfo
static const Builtin::Info BuiltinInfo[]
Definition: Builtins.cpp:20
clang::ObjCMethodDecl::param_const_iterator
const ParmVarDecl *const * param_const_iterator
Definition: DeclObjC.h:352
clang::Declarator::getDeclSpec
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:1910
clang::CXXRecordDecl::getDescribedClassTemplate
ClassTemplateDecl * getDescribedClassTemplate() const
Retrieves the class template that is described by this class declaration.
Definition: DeclCXX.cpp:1810
checkNewAttributesAfterDef
static void checkNewAttributesAfterDef(Sema &S, Decl *New, const Decl *Old)
checkNewAttributesAfterDef - If we already have a definition, check that there are no new attributes ...
Definition: SemaDecl.cpp:2861
clang::Sema::ActOnFinishFunctionBody
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:14674
clang::CanQual::getTypePtr
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Definition: CanonicalType.h:83
clang::ASTContext::getAssumedTemplateName
TemplateName getAssumedTemplateName(DeclarationName Name) const
Retrieve a template name representing an unqualified-id that has been assumed to name a template for ...
Definition: ASTContext.cpp:8986
APSInt
llvm::APSInt APSInt
Definition: ByteCodeEmitter.cpp:19
clang::Redeclarable::setPreviousDecl
void setPreviousDecl(decl_type *PrevDecl)
Set the previous declaration.
Definition: Decl.h:4634
U
clang::Sema::LookupTagName
@ LookupTagName
Tag name lookup, which finds the names of enums, classes, structs, and unions.
Definition: Sema.h:4308
synthesizeCurrentNestedNameSpecifier
static NestedNameSpecifier * synthesizeCurrentNestedNameSpecifier(ASTContext &Context, DeclContext *DC)
Definition: SemaDecl.cpp:548
clang::ParmVarDecl::setScopeInfo
void setScopeInfo(unsigned scopeDepth, unsigned parameterIndex)
Definition: Decl.h:1697
clang::CharSourceRange::getCharRange
static CharSourceRange getCharRange(SourceRange R)
Definition: SourceLocation.h:265
clang::LangAS::opencl_local
@ opencl_local
clang::Sema::CheckForFunctionRedefinition
void CheckForFunctionRedefinition(FunctionDecl *FD, const FunctionDecl *EffectiveDefinition=nullptr, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:14333
clang::IdentifierInfo::isStr
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
Definition: IdentifierTable.h:176
clang::Decl::getLexicalDeclContext
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:851
clang::Sema::ActOnTag
Decl * ActOnTag(Scope *S, unsigned TagSpec, TagUseKind TUK, SourceLocation KWLoc, CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc, const ParsedAttributesView &Attr, AccessSpecifier AS, SourceLocation ModulePrivateLoc, MultiTemplateParamsArg TemplateParameterLists, bool &OwnedDecl, bool &IsDependent, SourceLocation ScopedEnumKWLoc, bool ScopedEnumUsesClassTag, TypeResult UnderlyingType, bool IsTypeSpecifier, bool IsTemplateParamOrArg, SkipBodyInfo *SkipBody=nullptr)
This is invoked when we see 'struct foo' or 'struct {'.
Definition: SemaDecl.cpp:15836
clang::Sema::LookupMemberName
@ LookupMemberName
Member name lookup, which finds the names of class/struct/union members.
Definition: Sema.h:4313
clang::Type::isLiteralType
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2566
clang::Sema::ActOnTagDefinitionError
void ActOnTagDefinitionError(Scope *S, Decl *TagDecl)
ActOnTagDefinitionError - Invoked when there was an unrecoverable error parsing the definition of a t...
Definition: SemaDecl.cpp:16919
clang::VarDecl::isInline
bool isInline() const
Whether this variable is (C++1z) inline.
Definition: Decl.h:1460
clang::VarDecl::isParameterPack
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2554
CheckPoppedLabel
static void CheckPoppedLabel(LabelDecl *L, Sema &S)
Definition: SemaDecl.cpp:2049
clang::FunctionTemplateDecl
Declaration of a template function.
Definition: DeclTemplate.h:979
clang::ASTContext::getObjCIdType
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2030
llvm::MutableArrayRef
Definition: LLVM.h:35
clang::ASTContext::setNonKeyFunction
void setNonKeyFunction(const CXXMethodDecl *method)
Observe that the given method cannot be a key function.
Definition: RecordLayoutBuilder.cpp:3387
clang::Expr::getIntegerConstantExpr
Optional< llvm::APSInt > getIntegerConstantExpr(const ASTContext &Ctx, SourceLocation *Loc=nullptr, bool isEvaluated=true) const
isIntegerConstantExpr - Return the value if this expression is a valid integer constant expression.
Definition: ExprConstant.cpp:15700
clang::Type::isReferenceType
bool isReferenceType() const
Definition: Type.h:6762
clang::FunctionDecl::setConstexprKind
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2286
clang::CallExpr::getCallee
Expr * getCallee()
Definition: Expr.h:3003
clang::AttributeFactory
A factory, from which one makes pools, from which one creates individual attributes which are dealloc...
Definition: ParsedAttr.h:727
CheckTargetCausesMultiVersioning
static bool CheckTargetCausesMultiVersioning(Sema &S, FunctionDecl *OldFD, FunctionDecl *NewFD, const TargetAttr *NewTA, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Definition: SemaDecl.cpp:10670
clang::IntegerLiteral
Definition: Expr.h:1494
clang::VarDecl::hasInit
bool hasInit() const
Definition: Decl.cpp:2299
clang::QualType::hasNonTrivialObjCLifetime
bool hasNonTrivialObjCLifetime() const
Definition: Type.h:1126
diagnoseOpenCLTypes
static bool diagnoseOpenCLTypes(Sema &Se, VarDecl *NewVD)
Returns true if there hasn't been any invalid type diagnosed.
Definition: SemaDecl.cpp:6976
Template.h
clang::prec::Unknown
@ Unknown
Definition: OperatorPrecedence.h:27
clang::ast_matchers::expr
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
Definition: ASTMatchersInternal.cpp:890
clang::LangOptions::isCompatibleWithMSVC
bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const
Definition: LangOptions.h:464
clang::Sema::MergeSYCLUsesAspectsAttr
SYCLUsesAspectsAttr * MergeSYCLUsesAspectsAttr(Decl *D, const SYCLUsesAspectsAttr &A)
clang::DeclSpec::isNoreturnSpecified
bool isNoreturnSpecified() const
Definition: DeclSpec.h:591
clang::Sema::getShadowedDeclaration
NamedDecl * getShadowedDeclaration(const TypedefNameDecl *D, const LookupResult &R)
Return the declaration shadowed by the given typedef D, or null if it doesn't shadow any declaration ...
Definition: SemaDecl.cpp:7831
clang::Type::isBitIntType
bool isBitIntType() const
Definition: Type.h:6992
clang::ast_matchers::attr
const internal::VariadicAllOfMatcher< Attr > attr
Matches attributes.
Definition: ASTMatchersInternal.cpp:1030
hasDefinition
static bool hasDefinition(const ObjCObjectPointerType *ObjPtr)
Definition: DynamicTypeChecker.cpp:145
clang::InheritableAttr::setInherited
void setInherited(bool I)
Definition: Attr.h:150
clang::Sema::RebuildExprInCurrentInstantiation
ExprResult RebuildExprInCurrentInstantiation(Expr *E)
Definition: SemaTemplate.cpp:10832
clang::Decl::isFunctionOrFunctionTemplate
bool isFunctionOrFunctionTemplate() const
Whether this declaration is a function or function template.
Definition: DeclBase.h:1050
clang::Expr::isTypeDependent
bool isTypeDependent() const
Determines whether the type of this expression depends on.
Definition: Expr.h:185
clang::CXXRecordDecl::getLambdaCaptureDefault
LambdaCaptureDefault getLambdaCaptureDefault() const
Definition: DeclCXX.h:1040
clang::FunctionDecl::getConstexprKind
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2289
clang::VarDecl::setTSCSpec
void setTSCSpec(ThreadStorageClassSpecifier TSC)
Definition: Decl.h:1089
clang::RecordType
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:4649
getHeaderName
static StringRef getHeaderName(Builtin::Context &BuiltinInfo, unsigned ID, ASTContext::GetBuiltinTypeError Error)
Definition: SemaDecl.cpp:2178
haveIncompatibleLanguageLinkages
static bool haveIncompatibleLanguageLinkages(const T *Old, const T *New)
Definition: SemaDecl.cpp:3297
clang::DeclSpec::getVolatileSpecLoc
SourceLocation getVolatileSpecLoc() const
Definition: DeclSpec.h:550
clang::VarTemplateDecl::Create
static VarTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, VarDecl *Decl)
Create a variable template node.
Definition: DeclTemplate.cpp:1171
clang::Sema::computeNRVO
void computeNRVO(Stmt *Body, sema::FunctionScopeInfo *Scope)
Given the set of return statements within a function body, compute the variables that are subject to ...
Definition: SemaDecl.cpp:14611
clang::FunctionDecl::isCPUDispatchMultiVersion
bool isCPUDispatchMultiVersion() const
True if this function is a multiversioned dispatch function as a part of the cpu_specific/cpu_dispatc...
Definition: Decl.cpp:3296
clang::Module
Describes a module or submodule.
Definition: Module.h:96
clang::Sema::ActOnNameClassifiedAsUndeclaredNonType
ExprResult ActOnNameClassifiedAsUndeclaredNonType(IdentifierInfo *Name, SourceLocation NameLoc)
Act on the result of classifying a name as an undeclared (ADL-only) non-type declaration.
Definition: SemaDecl.cpp:1225
DeclTemplate.h
clang::DeclarationName::getCXXOverloadedOperator
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
Definition: DeclarationName.h:460
clang::Type::isSignedIntegerOrEnumerationType
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2040
clang::Sema::SkipBodyInfo::New
NamedDecl * New
Definition: Sema.h:2687
clang::Sema::SkipBodyInfo::ShouldSkip
bool ShouldSkip
Definition: Sema.h:2684
clang::FunctionDecl::hasSkippedBody
bool hasSkippedBody() const
True if the function was a definition but its body was skipped.
Definition: Decl.h:2425
hasSimilarParameters
static bool hasSimilarParameters(ASTContext &Context, FunctionDecl *Declaration, FunctionDecl *Definition, SmallVectorImpl< unsigned > &Params)
hasSimilarParameters - Determine whether the C++ functions Declaration and Definition have "nearly" m...
Definition: SemaDecl.cpp:5675
getOpenCLKernelParameterType
static OpenCLParamType getOpenCLKernelParameterType(Sema &S, QualType PT)
Definition: SemaDecl.cpp:8915
clang::OverridingMethods::iterator
MapType::iterator iterator
Definition: CXXInheritance.h:277
clang::Module::ModulePartitionInterface
@ ModulePartitionInterface
This is a C++ 20 module partition interface.
Definition: Module.h:116
clang::Builtin::Context::performsCallback
bool performsCallback(unsigned ID, llvm::SmallVectorImpl< int > &Encoding) const
Determine whether this builtin has callback behavior (see llvm::AbstractCallSites for details).
Definition: Builtins.cpp:165
clang::FTIHasNonVoidParameters
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:36
clang::TargetCXXABI::canKeyFunctionBeInline
bool canKeyFunctionBeInline() const
Can an out-of-line inline function serve as a key function?
Definition: TargetCXXABI.h:240
clang::Sema::ActOnTagFinishDefinition
void ActOnTagFinishDefinition(Scope *S, Decl *TagDecl, SourceRange BraceRange)
ActOnTagFinishDefinition - Invoked once we have finished parsing the definition of a tag (enumeration...
Definition: SemaDecl.cpp:16844
clang::UsingShadowDecl::getIntroducer
BaseUsingDecl * getIntroducer() const
Gets the (written or instantiated) using declaration that introduced this declaration.
Definition: DeclCXX.cpp:2985
clang::PartialDiagnosticAt
std::pair< SourceLocation, PartialDiagnostic > PartialDiagnosticAt
A partial diagnostic along with the source location where this diagnostic occurs.
Definition: PartialDiagnostic.h:205
clang::TemplateArgumentListInfo
A convenient class for passing around template argument information.
Definition: TemplateBase.h:563
clang::Linkage
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:23
clang::Declarator::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:1946
clang::DeclSpec::isExternInLinkageSpec
bool isExternInLinkageSpec() const
Definition: DeclSpec.h:444
clang::Decl::getAccess
AccessSpecifier getAccess() const
Definition: DeclBase.h:472
clang::ThreadStorageClassSpecifier
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:220
clang::Type::getAsTagDecl
TagDecl * getAsTagDecl() const
Retrieves the TagDecl that this type refers to, either because the type is a TagType or because it is...
Definition: Type.cpp:1768
GetDiagnosticTypeSpecifierID
static unsigned GetDiagnosticTypeSpecifierID(DeclSpec::TST T)
Definition: SemaDecl.cpp:4764
ExitFunctionBodyRAII
RAII object that pops an ExpressionEvaluationContext when exiting a function body.
Definition: SemaDecl.cpp:14680
clang::Type::isMemberFunctionPointerType
bool isMemberFunctionPointerType() const
Definition: Type.h:6802
clang::ASTContext::getNameForTemplate
DeclarationNameInfo getNameForTemplate(TemplateName Name, SourceLocation NameLoc) const
Definition: ASTContext.cpp:6092
clang::FunctionDecl::isTrivial
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2207
clang::Sema::NameClassification
Definition: Sema.h:2762
clang::TagTypeKind
TagTypeKind
The kind of a tag type.
Definition: Type.h:5386
clang::Decl::specific_attrs
llvm::iterator_range< specific_attr_iterator< T > > specific_attrs() const
Definition: DeclBase.h:523
clang::BlockDecl
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4179
clang::Sema::BuildAnonymousStructOrUnion
Decl * BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS, AccessSpecifier AS, RecordDecl *Record, const PrintingPolicy &Policy)
BuildAnonymousStructOrUnion - Handle the declaration of an anonymous structure or union.
Definition: SemaDecl.cpp:5206
clang::NSAPI::ClassId_NSObject
@ ClassId_NSObject
Definition: NSAPI.h:30
clang::QualType::getAddressSpace
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:6623
clang::DeclSpec::getTypeSpecType
TST getTypeSpecType() const
Definition: DeclSpec.h:476
clang::Sema::MergeVarDecl
void MergeVarDecl(VarDecl *New, LookupResult &Previous)
MergeVarDecl - We just parsed a variable 'New' which has the same name and scope as a previous declar...
Definition: SemaDecl.cpp:4247
clang::Sema::ActOnLastBitfield
void ActOnLastBitfield(SourceLocation DeclStart, SmallVectorImpl< Decl * > &AllIvarDecls)
ActOnLastBitfield - This routine handles synthesized bitfields rules for class and class extensions.
Definition: SemaDecl.cpp:17530
clang::ConstexprSpecKind::Consteval
@ Consteval
clang::UnqualifiedId::Kind
UnqualifiedIdKind Kind
Describes the kind of unqualified-id parsed.
Definition: DeclSpec.h:957
clang::Decl::getKind
Kind getKind() const
Definition: DeclBase.h:427
clang::ASTContext::getAsIncompleteArrayType
const IncompleteArrayType * getAsIncompleteArrayType(QualType T) const
Definition: ASTContext.h:2693
clang::C11
@ C11
Definition: LangStandard.h:45
clang::ASTContext::getDefaultCallingConvention
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
Definition: ASTContext.cpp:11628
clang::BinaryOperator
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3861
clang::DeclContext::getEnclosingNamespaceContext
DeclContext * getEnclosingNamespaceContext()
Retrieve the nearest enclosing namespace context.
Definition: DeclBase.cpp:1810
clang::Decl::setAccess
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:467
clang::FunctionDecl::getTemplatedKind
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3689
clang::Sema::CreateParsedType
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6445
clang::QualType::isObjCGCStrong
bool isObjCGCStrong() const
true when Type is objc's strong.
Definition: Type.h:1117
Id
int Id
Definition: ASTDiff.cpp:191
clang::VarDecl::isStaticLocal
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1124
clang::TagDecl::castFromDeclContext
static TagDecl * castFromDeclContext(const DeclContext *DC)
Definition: Decl.h:3604
clang::DeclSpec::UpdateTypeRep
void UpdateTypeRep(ParsedType Rep)
Definition: DeclSpec.h:715
clang::format::encoding::Encoding
Encoding
Definition: Encoding.h:27
clang::Qualifiers::OCL_Strong
@ OCL_Strong
Assigning into this object requires the old value to be released and the new value to be retained.
Definition: Type.h:175
clang::Type::isNullPtrType
bool isNullPtrType() const
Definition: Type.h:7082
clang::XRayInstrKind::None
constexpr XRayInstrMask None
Definition: XRayInstr.h:38
clang::DeclContext::getDeclKind
Decl::Kind getDeclKind() const
Definition: DeclBase.h:1865
clang::DeclSpec::UpdateExprRep
void UpdateExprRep(Expr *Rep)
Definition: DeclSpec.h:719
clang::Builtin::Context::getHeaderName
const char * getHeaderName(unsigned ID) const
If this is a library function that comes from a specific header, retrieve that header name.
Definition: Builtins.h:186
clang::Scope
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
clang::Decl::FOK_None
@ FOK_None
Not a friend object.
Definition: DeclBase.h:1142
clang::Sema::EnterDeclaratorContext
void EnterDeclaratorContext(Scope *S, DeclContext *DC)
EnterDeclaratorContext - Used when we must lookup names in the context of a declarator's nested name ...
Definition: SemaDecl.cpp:1340
clang::TemplateIdAnnotation::RAngleLoc
SourceLocation RAngleLoc
The location of the '>' after the template argument list.
Definition: ParsedTemplate.h:182
clang::UnaryOperator::isIncrementDecrementOp
static bool isIncrementDecrementOp(Opcode Op)
Definition: Expr.h:2317
clang::Declarator::getAsmLabel
Expr * getAsmLabel() const
Definition: DeclSpec.h:2545
clang::Scope::isDeclScope
bool isDeclScope(const Decl *D) const
isDeclScope - Return true if this is the scope that the specified decl is declared in.
Definition: Scope.h:340
clang::CXXScopeSpec::isValid
bool isValid() const
A scope specifier is present, and it refers to a real scope.
Definition: DeclSpec.h:197
clang::syntax::NodeRole::Callee
@ Callee
clang::DeclarationName::CXXDestructorName
@ CXXDestructorName
Definition: DeclarationName.h:205
clang::FunctionType::ExtInfo::getNoReturn
bool getNoReturn() const
Definition: Type.h:3720
clang::DeclaratorDecl::getSourceRange
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition: Decl.cpp:1990
clang::Type::isObjCIdType
bool isObjCIdType() const
Definition: Type.h:6911
clang::DeclSpec::TST_interface
static const TST TST_interface
Definition: DeclSpec.h:286
clang::ASTContext::getAsArrayType
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
Definition: ASTContext.cpp:6678
clang::SourceRange::getEnd
SourceLocation getEnd() const
Definition: SourceLocation.h:220
clang::Declarator::isFirstDeclarationOfMember
bool isFirstDeclarationOfMember()
Returns true if this declares a real member and not a friend.
Definition: DeclSpec.h:2588
clang::Sema::RequireNonAbstractType
bool RequireNonAbstractType(SourceLocation Loc, QualType T, TypeDiagnoser &Diagnoser)
Definition: SemaDeclCXX.cpp:5793
clang::AS_public
@ AS_public
Definition: Specifiers.h:109
clang::Type::isFunctionPointerType
bool isFunctionPointerType() const
Definition: Type.h:6784
clang::threadSafety::sx::toString
std::string toString(const til::SExpr *E)
Definition: ThreadSafetyCommon.h:89
clang::DeclSpec::getUnalignedSpecLoc
SourceLocation getUnalignedSpecLoc() const
Definition: DeclSpec.h:552
clang::Decl::setAttrs
void setAttrs(const AttrVec &Attrs)
Definition: DeclBase.h:485
clang::ASTContext::PSF_Read
@ PSF_Read
Definition: ASTContext.h:3263
clang::Sema::ActOnField
Decl * ActOnField(Scope *S, Decl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth)
ActOnField - Each field of a C struct/union is passed into this in order to create a FieldDecl object...
Definition: SemaDecl.cpp:17034
clang::FunctionDecl::getReturnTypeSourceRange
SourceRange getReturnTypeSourceRange() const
Attempt to compute an informative source range covering the function return type.
Definition: Decl.cpp:3569
clang::sema::CapturingScopeInfo::ImpCap_None
@ ImpCap_None
Definition: ScopeInfo.h:666
clang::ParamIdx
A single parameter index whose accessors require each use to make explicit the parameter index encodi...
Definition: Attr.h:230
clang::TemplateSpecializationType::anyInstantiationDependentTemplateArguments
static bool anyInstantiationDependentTemplateArguments(ArrayRef< TemplateArgumentLoc > Args)
Definition: Type.cpp:3670
clang::InitListExpr::children
child_range children()
Definition: Expr.h:5031
clang::ASTContext::DependentTy
CanQualType DependentTy
Definition: ASTContext.h:1120
clang::Sema::PushDeclContext
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1305
clang::VarDecl::isStaticDataMember
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition: Decl.h:1199
clang::TagDecl::getInnerLocStart
SourceLocation getInnerLocStart() const
Return SourceLocation representing start of source range ignoring outer template declarations.
Definition: Decl.h:3418
filterNonConflictingPreviousTypedefDecls
static void filterNonConflictingPreviousTypedefDecls(Sema &S, TypedefNameDecl *Decl, LookupResult &Previous)
Typedef declarations don't have linkage, but they still denote the same entity if their types are the...
Definition: SemaDecl.cpp:2300
clang::FPOptionsOverride
Represents difference between two FPOptions values.
Definition: LangOptions.h:654
clang::FunctionDecl::isThisDeclarationADefinition
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition: Decl.h:2151
clang::SC_Extern
@ SC_Extern
Definition: Specifiers.h:236
clang::CopiedTypeVisitor
Definition: NonTrivialTypeVisitor.h:78
clang::ASTContext
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:208
checkForConflictWithNonVisibleExternC
static bool checkForConflictWithNonVisibleExternC(Sema &S, const T *ND, LookupResult &Previous)
Apply special rules for handling extern "C" declarations.
Definition: SemaDecl.cpp:8107
clang::MultiTemplateParamsArg
MutableArrayRef< TemplateParameterList * > MultiTemplateParamsArg
Definition: Ownership.h:276
clang::Sema::ActOnSkippedFunctionBody
Decl * ActOnSkippedFunctionBody(Decl *Decl)
Definition: SemaDecl.cpp:14664
clang::Sema::FinalizeDeclaration
void FinalizeDeclaration(Decl *D)
FinalizeDeclaration - called by ParseDeclarationAfterDeclarator to perform any semantic actions neces...
Definition: SemaDecl.cpp:13593
clang::Sema::canFullyTypeCheckRedeclaration
bool canFullyTypeCheckRedeclaration(ValueDecl *NewD, ValueDecl *OldD, QualType NewT, QualType OldT)
Determines if we can perform a correct type check for D as a redeclaration of PrevDecl.
Definition: SemaDecl.cpp:10327
clang::CPlusPlus
@ CPlusPlus
Definition: LangStandard.h:48
clang::Sema::CheckForConstantInitializer
bool CheckForConstantInitializer(Expr *e, QualType t)
type checking declaration initializers (C99 6.7.8)
Definition: SemaDecl.cpp:11561
clang::Sema::warnOnReservedIdentifier
void warnOnReservedIdentifier(const NamedDecl *D)
Definition: SemaDecl.cpp:5786
clang::ArrayType
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:2898
CXXFieldCollector.h
clang::DeclarationNameTable::getCXXOperatorName
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
Definition: DeclarationName.h:637
isOutOfScopePreviousDeclaration
static bool isOutOfScopePreviousDeclaration(NamedDecl *, DeclContext *, ASTContext &)
Determines whether the given declaration is an out-of-scope previous declaration.
Definition: SemaDecl.cpp:6495
clang::Decl::FOK_Undeclared
@ FOK_Undeclared
A friend of a previously-undeclared entity.
Definition: DeclBase.h:1144
clang::AttributedType::getNullabilityAttrKind
static Kind getNullabilityAttrKind(NullabilityKind kind)
Retrieve the attribute kind corresponding to the given nullability kind.
Definition: Type.h:4757
clang::NamedDecl::getVisibility
Visibility getVisibility() const
Determines the visibility of this entity.
Definition: Decl.h:417
clang::DeclaratorContext::Member
@ Member
clang::Sema::DeduceVariableDeclarationType
bool DeduceVariableDeclarationType(VarDecl *VDecl, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12061
clang::ParenTypeLoc
Definition: TypeLoc.h:1145
clang::Sema::mergeOptimizeNoneAttr
OptimizeNoneAttr * mergeOptimizeNoneAttr(Decl *D, const AttributeCommonInfo &CI)
clang::Qualifiers::removeConst
void removeConst()
Definition: Type.h:266
clang::DependentNameTypeLoc
Definition: TypeLoc.h:2319
recoverFromTypeInKnownDependentBase
static ParsedType recoverFromTypeInKnownDependentBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc)
Definition: SemaDecl.cpp:237
clang::DecompositionDecl
A decomposition declaration.
Definition: DeclCXX.h:4036
clang::DeclaratorChunk::FunctionTypeInfo
Definition: DeclSpec.h:1276
clang::QualType::isNonWeakInMRRWithObjCWeak
bool isNonWeakInMRRWithObjCWeak(const ASTContext &Context) const
Definition: Type.cpp:2509
clang::CXXBaseSpecifier::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclCXX.h:190
clang::WeakInfo
Captures information about a #pragma weak directive.
Definition: Weak.h:25
clang::Declarator::getDecompositionDeclarator
const DecompositionDeclarator & getDecompositionDeclarator() const
Definition: DeclSpec.h:1931
clang::ReservedIdentifierStatus
ReservedIdentifierStatus
Definition: IdentifierTable.h:43
clang::FunctionDecl::isCPUSpecificMultiVersion
bool isCPUSpecificMultiVersion() const
True if this function is a multiversioned processor specific function as a part of the cpu_specific/c...
Definition: Decl.cpp:3300
clang::DeclSpec::hasConstexprSpecifier
bool hasConstexprSpecifier() const
Definition: DeclSpec.h:759
clang::DeclSpec::ClearStorageClassSpecs
void ClearStorageClassSpecs()
Definition: DeclSpec.h:454
clang::Sema::mergeTypeVisibilityAttr
TypeVisibilityAttr * mergeTypeVisibilityAttr(Decl *D, const AttributeCommonInfo &CI, TypeVisibilityAttr::VisibilityType Vis)
clang::Type::getAs
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7263
clang::DiagnosticsEngine::Error
@ Error
Definition: Diagnostic.h:200
clang::TargetInfo::getMaxTLSAlign
unsigned getMaxTLSAlign() const
Return the maximum alignment (in bits) of a TLS variable.
Definition: TargetInfo.h:1413
clang::Sema::SFINAETrap::hasErrorOccurred
bool hasErrorOccurred() const
Determine whether any SFINAE errors have been trapped.
Definition: Sema.h:9554
clang::DeclContext::makeDeclVisibleInContext
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1847
clang::LookupResult::makeFilter
Filter makeFilter()
Create a filter for this result set.
Definition: Lookup.h:682
clang::CXXRecordDecl::getNumBases
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:590
clang::Decl::isInvalidDecl
bool isInvalidDecl() const
Definition: DeclBase.h:552
clang::ASTContext::getAsVariableArrayType
const VariableArrayType * getAsVariableArrayType(QualType T) const
Definition: ASTContext.h:2690
clang::Sema::DeviceDiagnosticReason::Esimd
@ Esimd
ESIMD specific diagnostic.
clang::CallExpr::getArg
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition: Expr.h:3044
findRecordWithDependentBasesOfEnclosingMethod
static const CXXRecordDecl * findRecordWithDependentBasesOfEnclosingMethod(const DeclContext *DC)
Find the parent class with dependent bases of the innermost enclosing method context.
Definition: SemaDecl.cpp:568
clang::Sema::AlignPackInfo
Definition: Sema.h:665
clang::Decl::isInExportDeclContext
bool isInExportDeclContext() const
Whether this declaration was exported in a lexical context.
Definition: DeclBase.cpp:998
clang::Module::DefinitionLoc
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:102
clang::VarDecl::isOutOfLine
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a static data member.
Definition: Decl.cpp:2339
clang::FunctionType::getCallConv
CallingConv getCallConv() const
Definition: Type.h:3835
clang::DeclarationNameInfo::setName
void setName(DeclarationName N)
setName - Sets the embedded declaration name.
Definition: DeclarationName.h:782
clang::TagDecl::isThisDeclarationADefinition
bool isThisDeclarationADefinition() const
Return true if this declaration is a completion definition of the type.
Definition: Decl.h:3432
clang::Sema::AddInitializerToDecl
void AddInitializerToDecl(Decl *dcl, Expr *init, bool DirectInit)
AddInitializerToDecl - Adds the initializer Init to the declaration dcl.
Definition: SemaDecl.cpp:12371
clang::Expr::containsErrors
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:238
clang::DeclSpec::TST_class
static const TST TST_class
Definition: DeclSpec.h:287
clang::DeclSpec::SCS_typedef
@ SCS_typedef
Definition: DeclSpec.h:235
clang::DeclContext::containsDecl
bool containsDecl(Decl *D) const
Checks whether a declaration is in this context.
Definition: DeclBase.cpp:1444
clang::ASTContext::getObjCInterfaceType
QualType getObjCInterfaceType(const ObjCInterfaceDecl *Decl, ObjCInterfaceDecl *PrevDecl=nullptr) const
getObjCInterfaceType - Return the unique reference to the type for the specified ObjC interface decl.
Definition: ASTContext.cpp:5521
clang::Sema::Diags
DiagnosticsEngine & Diags
Definition: Sema.h:589
clang::RecordDecl::setHasNonTrivialToPrimitiveDestructCUnion
void setHasNonTrivialToPrimitiveDestructCUnion(bool V)
Definition: Decl.h:4020
clang::Sema::ClassifyName
NameClassification ClassifyName(Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc, const Token &NextToken, CorrectionCandidateCallback *CCC=nullptr)
Perform name lookup on the given name, classifying it based on the results of name lookup and the fol...
Definition: SemaDecl.cpp:859
clang::TagDecl::setTypedefNameForAnonDecl
void setTypedefNameForAnonDecl(TypedefNameDecl *TDD)
Definition: Decl.cpp:4333
clang::Attr::getKind
attr::Kind getKind() const
Definition: Attr.h:84
clang::FunctionProtoType::getParamType
QualType getParamType(unsigned i) const
Definition: Type.h:4112
clang::Declarator::AddTypeInfo
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition: DeclSpec.h:2211
clang::Sema::DiagRuntimeBehavior
bool DiagRuntimeBehavior(SourceLocation Loc, const Stmt *Statement, const PartialDiagnostic &PD)
Conditionally issue a diagnostic based on the current evaluation context.
Definition: SemaExpr.cpp:19468
clang::UnqualifiedIdKind::IK_LiteralOperatorId
@ IK_LiteralOperatorId
A user-defined literal name, e.g., operator "" _i.
clang::LambdaCaptureDefault
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition: Lambda.h:22
clang::LabelDecl
Represents the declaration of a label.
Definition: Decl.h:495
clang::CallExpr::isCallToStdMove
bool isCallToStdMove() const
Definition: Expr.h:3183
clang::FunctionDecl::setWillHaveBody
void setWillHaveBody(bool V=true)
Definition: Decl.h:2432
clang::CXXRecordDecl::markAbstract
void markAbstract()
Definition: DeclCXX.h:1810
ModuleLoader.h
DelayedDiagnostic.h
clang::Decl::getCanonicalDecl
virtual Decl * getCanonicalDecl()
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclBase.h:909
clang::TypoCorrection::isKeyword
bool isKeyword() const
Definition: TypoCorrection.h:202
clang::Token::is
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition: Token.h:97
isFromSystemHeader
static bool isFromSystemHeader(SourceManager &SM, const Decl *D)
Returns true if the declaration is declared in a system header or from a system macro.
Definition: SemaDecl.cpp:5781
clang::sema::FunctionScopeInfo::HasPotentialAvailabilityViolations
bool HasPotentialAvailabilityViolations
Whether we make reference to a declaration that could be unavailable.
Definition: ScopeInfo.h:138
isDeclExternC
static bool isDeclExternC(const Decl *D)
Returns true if given declaration has external C language linkage.
Definition: SemaDecl.cpp:6966
clang::Sema::MergeReqdWorkGroupSizeAttr
ReqdWorkGroupSizeAttr * MergeReqdWorkGroupSizeAttr(Decl *D, const ReqdWorkGroupSizeAttr &A)
clang::ASTContext::UnknownAnyTy
CanQualType UnknownAnyTy
Definition: ASTContext.h:1120
clang::ConstantArrayType::getMaxSizeBits
static unsigned getMaxSizeBits(const ASTContext &Context)
Determine the maximum number of active bits that an array's size can require, which limits the maximu...
Definition: Type.cpp:176
clang::Stmt::children
child_range children()
Definition: Stmt.cpp:285
clang::IntegerLiteral::Create
static IntegerLiteral * Create(const ASTContext &C, const llvm::APInt &V, QualType type, SourceLocation l)
Returns a new integer literal with value 'V' and type 'type'.
Definition: Expr.cpp:953
clang::EnumConstantDecl::getInitVal
const llvm::APSInt & getInitVal() const
Definition: Decl.h:3075
clang::DiagNullabilityKind
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
Definition: Diagnostic.h:1524
clang::BinaryConditionalOperator
BinaryConditionalOperator - The GNU extension to the conditional operator which allows the middle ope...
Definition: Expr.h:4261
clang::Sema::PDiag
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
clang::ASTContext::getTypeSize
uint64_t getTypeSize(QualType T) const
Return the size of the specified (complete) type T, in bits.
Definition: ASTContext.h:2282
clang::TypedefNameDecl::getUnderlyingType
QualType getUnderlyingType() const
Definition: Decl.h:3239
clang::ASTContext::getAutoDeductType
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
Definition: ASTContext.cpp:5797
clang::TypoCorrection::getEditDistance
unsigned getEditDistance(bool Normalized=true) const
Gets the "edit distance" of the typo correction from the typo.
Definition: TypoCorrection.h:128
clang::ParenListExpr::getNumExprs
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5616
clang::CXXDestructorDecl
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2688
mergeParamDeclTypes
static void mergeParamDeclTypes(ParmVarDecl *NewParam, const ParmVarDecl *OldParam, Sema &S)
Definition: SemaDecl.cpp:3221
clang::ImplicitCastExpr::Create
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2028
clang::Sema::GetTypeFromParser
static QualType GetTypeFromParser(ParsedType Ty, TypeSourceInfo **TInfo=nullptr)
Definition: SemaType.cpp:3020
clang::DeclContext::isTranslationUnit
bool isTranslationUnit() const
Definition: DeclBase.h:1947
clang::AutoType
Represents a C++11 auto or C++14 decltype(auto) type, possibly constrained by a type-constraint.
Definition: Type.h:5050
clang::DeclRefExpr::getDecl
ValueDecl * getDecl()
Definition: Expr.h:1295
clang::NestedNameSpecifier::containsErrors
bool containsErrors() const
Whether this nested name specifier contains an error.
Definition: NestedNameSpecifier.cpp:246
clang::QualType::hasAddressSpace
bool hasAddressSpace() const
Check if this type has any address space qualifier.
Definition: Type.h:6618
hasParsedAttr
static bool hasParsedAttr(Scope *S, const Declarator &PD, ParsedAttr::Kind Kind)
Definition: SemaDecl.cpp:6924
clang::DeclSpec::isTypeSpecOwned
bool isTypeSpecOwned() const
Definition: DeclSpec.h:480
clang::Type::isFunctionType
bool isFunctionType() const
Definition: Type.h:6746
clang::UnresolvedLookupExpr::Create
static UnresolvedLookupExpr * Create(const ASTContext &Context, CXXRecordDecl *NamingClass, NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin, UnresolvedSetIterator End)
Definition: ExprCXX.cpp:369
clang::VariableArrayType::getSizeExpr
Expr * getSizeExpr() const
Definition: Type.h:3067
clang::Declarator::setInvalidType
void setInvalidType(bool Val=true)
Definition: DeclSpec.h:2556
clang::ParsedAttr
ParsedAttr - Represents a syntactic attribute.
Definition: ParsedAttr.h:240
clang::Type::isSizelessType
bool isSizelessType() const
As an extension, we classify types as one of "sized" or "sizeless"; every type is one or the other.
Definition: Type.cpp:2322
clang::UnqualifiedIdKind::IK_ConstructorName
@ IK_ConstructorName
A constructor name.
clang::VarDecl::hasExternalStorage
bool hasExternalStorage() const
Returns true if a variable has extern or private_extern storage.
Definition: Decl.h:1133
clang::CPlusPlus20
@ CPlusPlus20
Definition: LangStandard.h:52
Expr.h
clang::TargetInfo::validateCpuIs
virtual bool validateCpuIs(StringRef Name) const
Definition: TargetInfo.h:1364
clang::Sema::MergeFunctionDecl
bool MergeFunctionDecl(FunctionDecl *New, NamedDecl *&Old, Scope *S, bool MergeTypeWithOld)
MergeFunctionDecl - We just parsed a function 'New' from declarator D which has the same name and sco...
Definition: SemaDecl.cpp:3422
llvm::SmallString
Definition: LLVM.h:37
clang::Expr::EvalResult
EvalResult is a struct with detailed info about an evaluated expression.
Definition: Expr.h:612
bool
#define bool
Definition: stdbool.h:20
clang::Redeclarable::redecls
redecl_range redecls() const
Returns an iterator range for all the redeclarations of the same decl.
Definition: Redeclarable.h:296
clang::AttrVec
SmallVector< Attr *, 4 > AttrVec
AttrVec - A vector of Attr, which is how they are stored on the AST.
Definition: AttrIterator.h:28
clang::LangAS::opencl_constant
@ opencl_constant
clang::TemplateArgumentListInfo::setLAngleLoc
void setLAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:582
clang::Sema::GetNameForDeclarator
DeclarationNameInfo GetNameForDeclarator(Declarator &D)
GetNameForDeclarator - Determine the full declaration name for the given Declarator.
Definition: SemaDecl.cpp:5534
ASTContext.h
clang::ASTContext::getRecordType
QualType getRecordType(const RecordDecl *Decl) const
Definition: ASTContext.cpp:4641
clang::LCD_ByCopy
@ LCD_ByCopy
Definition: Lambda.h:24
clang::interp::Zero
bool Zero(InterpState &S, CodePtr OpPC)
Definition: Interp.h:814
clang::Sema::KernelNonConstStaticDataVariable
@ KernelNonConstStaticDataVariable
Definition: Sema.h:13682
clang::TypeDecl::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3169
clang::CallingConv
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:263
clang::DeclaratorDecl::setTemplateParameterListsInfo
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:1934
clang::DeclaratorChunk::FunctionTypeInfo::getDeclsInPrototype
ArrayRef< NamedDecl * > getDeclsInPrototype() const
Get the non-parameter decls defined within this function prototype.
Definition: DeclSpec.h:1491
clang::VarDecl
Represents a variable declaration or definition.
Definition: Decl.h:875
clang::FunctionProtoType::getParamTypes
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:4117
clang::Type::isStructureType
bool isStructureType() const
Definition: Type.cpp:563
clang::Sema::ActOnPragmaRedefineExtname
void ActOnPragmaRedefineExtname(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaRedefineExtname - Called on well formed #pragma redefine_extname oldname newname.
Definition: SemaDecl.cpp:18757
clang::ASTContext::setObjCClassRedefinitionType
void setObjCClassRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:1851
clang::ASTContext::getObjCClassType
QualType getObjCClassType() const
Represents the Objective-C Class type.
Definition: ASTContext.h:2052
clang::Declarator::setFunctionDefinitionKind
void setFunctionDefinitionKind(FunctionDefinitionKind Val)
Definition: DeclSpec.h:2572
clang::Sema::SkipBodyInfo
Definition: Sema.h:2680
shouldConsiderLinkage
static bool shouldConsiderLinkage(const VarDecl *VD)
Definition: SemaDecl.cpp:6900
diagnoseVarDeclTypeMismatch
static void diagnoseVarDeclTypeMismatch(Sema &S, VarDecl *New, VarDecl *Old)
Definition: SemaDecl.cpp:4100
clang::DeclSpec::isFriendSpecified
bool isFriendSpecified() const
Definition: DeclSpec.h:748
clang::Type::getPointeeType
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:625
clang::TagDecl
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3332
clang::Sema::ImplicitlyDefineFunction
NamedDecl * ImplicitlyDefineFunction(SourceLocation Loc, IdentifierInfo &II, Scope *S)
ImplicitlyDefineFunction - An undeclared identifier was used in a function call, forming a call to an...
Definition: SemaDecl.cpp:15117
clang::ConstexprSpecKind::Constexpr
@ Constexpr
clang::serialization::TypeID
uint32_t TypeID
An ID number that refers to a type in an AST file.
Definition: ASTBitCodes.h:85
clang::FunctionDecl::setHasInheritedPrototype
void setHasInheritedPrototype(bool P=true)
State that this function inherited its prototype from a previous declaration.
Definition: Decl.h:2278
clang::Declarator::hasInitializer
bool hasInitializer() const
Definition: DeclSpec.h:2585
clang::ObjCIvarDecl::Private
@ Private
Definition: DeclObjC.h:1928
clang::TemplateParameterList
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:69
clang::StringLiteral
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1767
clang::TargetInfo::isTLSSupported
bool isTLSSupported() const
Whether the target supports thread-local storage.
Definition: TargetInfo.h:1405
clang::DeclSpec::getStorageClassSpec
SCS getStorageClassSpec() const
Definition: DeclSpec.h:440
clang::TagDecl::setTemplateParameterListsInfo
void setTemplateParameterListsInfo(ASTContext &Context, ArrayRef< TemplateParameterList * > TPLists)
Definition: Decl.cpp:4408
clang::dataflow::var
static constexpr Variable var(Literal L)
Returns the variable of L.
Definition: WatchedLiteralsSolver.cpp:71
clang::TTK_Class
@ TTK_Class
The "class" keyword.
Definition: Type.h:5397
clang::CXXConstructExpr::getConstructor
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition: ExprCXX.h:1532
clang::Sema::TagUseKind
TagUseKind
Definition: Sema.h:3376
clang::ExprWithCleanups
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3359
clang::ASTContext::getLifetimeQualifiedType
QualType getLifetimeQualifiedType(QualType type, Qualifiers::ObjCLifetime lifetime)
Return a type with the given lifetime qualifier.
Definition: ASTContext.h:2146
clang::ASTContext::getCanonicalType
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2505
clang::TypeDecl
Represents a declaration of a type.
Definition: Decl.h:3142
clang::DeclaratorDecl::getTrailingRequiresClause
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:803
clang::Type::getAsCXXRecordDecl
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1760
clang::Sema::CheckRedeclarationInModule
bool CheckRedeclarationInModule(NamedDecl *New, NamedDecl *Old)
Definition: SemaDecl.cpp:1689
clang::TTK_Union
@ TTK_Union
The "union" keyword.
Definition: Type.h:5394
clang::tok::ObjCKeywordKind
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
Definition: TokenKinds.h:41
clang::TagDecl::isUnion
bool isUnion() const
Definition: Decl.h:3538
clang::VarDecl::isLocalVarDecl
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1169
clang::DeclaratorDecl::getQualifier
NestedNameSpecifier * getQualifier() const
Retrieve the nested-name-specifier that qualifies the name of this declaration, if it was present in ...
Definition: Decl.h:785
RecordKernelParam
@ RecordKernelParam
Definition: SemaDecl.cpp:8890
clang::DeclContext::isNamespace
bool isNamespace() const
Definition: DeclBase.h:1956
clang::Sema::LookupParsedName
bool LookupParsedName(LookupResult &R, Scope *S, CXXScopeSpec *SS, bool AllowBuiltinCreation=false, bool EnteringContext=false)
Performs name lookup for a name that was parsed in the source code, and may contain a C++ scope speci...
Definition: SemaLookup.cpp:2520
clang::VarDecl::setCXXForRangeDecl
void setCXXForRangeDecl(bool FRD)
Definition: Decl.h:1434
clang::DeclaratorDecl::getTypeSpecStartLoc
SourceLocation getTypeSpecStartLoc() const
Definition: Decl.cpp:1888
clang::Type::isVariablyModifiedType
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition: Type.h:2201
clang::CXXRecordDecl::bases
base_class_range bases()
Definition: DeclCXX.h:596
clang::Sema::DeviceDiagnosticReason
DeviceDiagnosticReason
Bitmask to contain the list of reasons a single diagnostic should be emitted, based on its language.
Definition: Sema.h:1878
clang::CXXDeductionGuideDecl::Create
static CXXDeductionGuideDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, ExplicitSpecifier ES, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, SourceLocation EndLocation, CXXConstructorDecl *Ctor=nullptr)
Definition: DeclCXX.cpp:2064
clang::DeclSpec::getNoreturnSpecLoc
SourceLocation getNoreturnSpecLoc() const
Definition: DeclSpec.h:592
clang::SC_Register
@ SC_Register
Definition: Specifiers.h:242
clang::CXXRecordDecl::captures
capture_const_range captures() const
Definition: DeclCXX.h:1066
clang::FunctionDecl::setPure
void setPure(bool P=true)
Definition: Decl.cpp:3071
mergeAlignedAttrs
static bool mergeAlignedAttrs(Sema &S, NamedDecl *New, Decl *Old)
Merge alignment attributes from Old to New, taking into account the special semantics of C11's _Align...
Definition: SemaDecl.cpp:2582
clang::Sema::getCurFPFeatures
FPOptions & getCurFPFeatures()
Definition: Sema.h:1776
clang::Sema::DeviceDiagnosticReason::CudaHost
@ CudaHost
clang::EnumConstantDecl
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3054
clang::FunctionType::ExtInfo::withCallingConv
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:3787
clang::DeclSpec::SetStorageClassSpec
bool SetStorageClassSpec(Sema &S, SCS SC, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
These methods set the specified attribute of the DeclSpec and return false if there was no error.
Definition: DeclSpec.cpp:618
SDK_Typedef
@ SDK_Typedef
Definition: SemaDecl.cpp:7772
clang::Type::isAtomicType
bool isAtomicType() const
Definition: Type.h:6891
clang::DeclSpec::TST_union
static const TST TST_union
Definition: DeclSpec.h:284
SDK_StaticMember
@ SDK_StaticMember
Definition: SemaDecl.cpp:7770
RebuildLambdaScopeInfo
static void RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator, Sema &S)
Definition: SemaDecl.cpp:14388
clang::ObjCContainerDecl::getIvarDecl
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition: DeclObjC.cpp:80
clang::AttributedTypeLoc
Type source information for an attributed type.
Definition: TypeLoc.h:860
clang::QualifierCollector
A qualifier set is used to build a set of qualifiers.
Definition: Type.h:6442
clang::ParsedType
OpaquePtr< QualType > ParsedType
An opaque type for threading parsed type information through the parser.
Definition: Ownership.h:243
clang::Decl::setNonMemberOperator
void setNonMemberOperator()
Specifies that this declaration is a C++ overloaded non-member.
Definition: DeclBase.h:1160
clang::ASTContext::getPromotedIntegerType
QualType getPromotedIntegerType(QualType PromotableType) const
Return the type that PromotableType will promote to: C99 6.3.1.1p2, assuming that PromotableType is a...
Definition: ASTContext.cpp:6957
clang::NestedNameSpecifierLoc
A C++ nested-name-specifier augmented with source location information.
Definition: NestedNameSpecifier.h:243
clang::Sema::ActOnMSVCUnknownTypeName
ParsedType ActOnMSVCUnknownTypeName(const IdentifierInfo &II, SourceLocation NameLoc, bool IsTemplateTypeArg)
Attempt to behave like MSVC in situations where lookup of an unqualified type name has failed in a de...
Definition: SemaDecl.cpp:578
clang::Redeclarable::getPreviousDecl
decl_type * getPreviousDecl()
Return the previous declaration of this declaration or NULL if this is the first declaration.
Definition: Redeclarable.h:204
clang::LookupResult::getLookupName
DeclarationName getLookupName() const
Gets the name to look up.
Definition: Lookup.h:243
clang::DeclContext::getLookupParent
DeclContext * getLookupParent()
Find the parent context of this context that will be used for unqualified name lookup.
Definition: DeclBase.cpp:1102
clang::OverridingMethods::overriding_iterator
SmallVectorImpl< UniqueVirtualMethod >::iterator overriding_iterator
Definition: CXXInheritance.h:289
clang::DeclSpec::SCS_register
@ SCS_register
Definition: DeclSpec.h:239
clang::Sema::MergeVarDeclTypes
void MergeVarDeclTypes(VarDecl *New, VarDecl *Old, bool MergeTypeWithOld)
MergeVarDeclTypes - We parsed a variable 'New' which has the same name and scope as a previous declar...
Definition: SemaDecl.cpp:4123
clang::CanQual< Type >
ExprCXX.h
clang::LookupResult::Filter::erase
void erase()
Erase the last element returned from this iterator.
Definition: Lookup.h:654
clang::Sema::isTagName
TypeSpecifierType isTagName(IdentifierInfo &II, Scope *S)
isTagName() - This method is called for error recovery purposes only to determine if the specified na...
Definition: SemaDecl.cpp:631
Base
clang::Sema::getObjCDeclContext
Decl * getObjCDeclContext() const
Definition: SemaDecl.cpp:18814
Label
std::string Label
Definition: UsingDeclarationsSorter.cpp:69
clang::LCD_None
@ LCD_None
Definition: Lambda.h:23
clang::DeclContext::isRecord
bool isRecord() const
Definition: DeclBase.h:1951
clang::FunctionDecl::getOverloadedOperator
OverloadedOperatorKind getOverloadedOperator() const
getOverloadedOperator - Which C++ overloaded operator this function represents, if any.
Definition: Decl.cpp:3675
clang::Redeclarable::isFirstDecl
bool isFirstDecl() const
True if this is the first declaration in its redeclaration chain.
Definition: Redeclarable.h:223
clang::FunctionDecl::Create
static FunctionDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation NLoc, DeclarationName N, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin=false, bool isInlineSpecified=false, bool hasWrittenPrototype=true, ConstexprSpecKind ConstexprKind=ConstexprSpecKind::Unspecified, Expr *TrailingRequiresClause=nullptr)
Definition: Decl.h:2028
clang::TagDecl::isCompleteDefinition
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3437
clang::DeclSpec::ClearTypeQualifiers
void ClearTypeQualifiers()
Clear out all of the type qualifiers.
Definition: DeclSpec.h:556
clang::Type::isEnumeralType
bool isEnumeralType() const
Definition: Type.h:6844
clang::DeclaratorChunk::FunctionTypeInfo::Params
ParamInfo * Params
Params - This is a pointer to a new[]'d array of ParamInfo objects that describe the parameters speci...
Definition: DeclSpec.h:1340
clang::operator<<
const StreamingDiagnostic & operator<<(const StreamingDiagnostic &DB, const ASTContext::SectionInfo &Section)
Insertion operator for diagnostics.
Definition: ASTContext.cpp:12297
clang::Decl::setImplicit
void setImplicit(bool I=true)
Definition: DeclBase.h:558
clang::Sema::isVisible
bool isVisible(const NamedDecl *D)
Determine whether a declaration is visible to name lookup.
Definition: Sema.h:2535
clang::Token::isNot
bool isNot(tok::TokenKind K) const
Definition: Token.h:98
clang::Sema::ActOnIvar
Decl * ActOnIvar(Scope *S, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, tok::ObjCKeywordKind visibility)
ActOnIvar - Each ivar field of an objective-c class is passed into this in order to create an IvarDec...
Definition: SemaDecl.cpp:17415
clang::QualType::hasQualifiers
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6577
clang::DeclSpec::ClearConstexprSpec
void ClearConstexprSpec()
Definition: DeclSpec.h:763
clang::LookupResult::Ambiguous
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition: Lookup.h:73
clang::sema::CapturingScopeInfo::ImpCaptureStyle
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:670
clang::Type::getAsAdjusted
const T * getAsAdjusted() const
Member-template getAsAdjusted<specific type>.
Definition: Type.h:7280
clang::sema::FunctionScopeInfo::ObjCShouldCallSuper
bool ObjCShouldCallSuper
A flag that is set when parsing a method that must call super's implementation, such as -dealloc,...
Definition: ScopeInfo.h:143
clang::Sema::IsValueInFlagEnum
bool IsValueInFlagEnum(const EnumDecl *ED, const llvm::APInt &Val, bool AllowMask) const
IsValueInFlagEnum - Determine if a value is allowed as part of a flag enum.
Definition: SemaDecl.cpp:18489
clang::Sema::DiagnoseFunctionSpecifiers
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6334
clang::Type::getPointeeOrArrayElementType
const Type * getPointeeOrArrayElementType() const
If this is a pointer type, return the pointee type.
Definition: Type.h:7220
clang::NamedDecl::hasLinkageBeenComputed
bool hasLinkageBeenComputed() const
True if something has required us to compute the linkage of this declaration.
Definition: Decl.h:452
clang::Sema::ActOnExitFunctionContext
void ActOnExitFunctionContext()
Definition: SemaDecl.cpp:1455
clang::NestedNameSpecifierLocBuilder
Class that aids in the construction of nested-name-specifiers along with source-location information ...
Definition: NestedNameSpecifier.h:356
clang::DeclSpec::getThreadStorageClassSpecLoc
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:450
clang::ASTContext::setObjCSelRedefinitionType
void setObjCSelRedefinitionType(QualType RedefType)
Set the user-written type that redefines 'SEL'.
Definition: ASTContext.h:1864
clang::DeclSpec::SCS_mutable
@ SCS_mutable
Definition: DeclSpec.h:241
clang::VarDecl::setDescribedVarTemplate
void setDescribedVarTemplate(VarTemplateDecl *Template)
Definition: Decl.cpp:2683
clang::MultiVersionKind::TargetClones
@ TargetClones
clang::Sema::DelayedDiagnostics::shouldDelayDiagnostics
bool shouldDelayDiagnostics()
Determines whether diagnostics should be delayed.
Definition: Sema.h:1116
clang::Sema::LookupName
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false)
Perform unqualified name lookup starting from a given scope.
Definition: SemaLookup.cpp:1985
clang::ObjCMessageExpr
An expression that sends a message to the given Objective-C object or class.
Definition: ExprObjC.h:940
clang::QualType::hasNonTrivialToPrimitiveDestructCUnion
bool hasNonTrivialToPrimitiveDestructCUnion() const
Check if this is or contains a C union that is non-trivial to destruct, which is a union that has a m...
Definition: Type.h:6638
isTemplate
static const GlobalDecl isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs)
Definition: ItaniumMangle.cpp:913
isFunctionDefinitionDiscarded
static bool isFunctionDefinitionDiscarded(Sema &S, FunctionDecl *FD)
Given that we are within the definition of the given function, will that definition behave like C99's...
Definition: SemaDecl.cpp:6855
clang::Sema::mergeEnforceTCBAttr
EnforceTCBAttr * mergeEnforceTCBAttr(Decl *D, const EnforceTCBAttr &AL)
clang::Declarator::isFunctionDeclarator
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2298
clang::QualType::getSingleStepDesugaredType
QualType getSingleStepDesugaredType(const ASTContext &Context) const
Return the specified type with one level of "sugar" removed from the type.
Definition: Type.h:994
clang::RecordDecl::isAnonymousStructOrUnion
bool isAnonymousStructOrUnion() const
Whether this is an anonymous struct or union.
Definition: Decl.h:3958
clang::Sema::getOpenCLOptions
OpenCLOptions & getOpenCLOptions()
Definition: Sema.h:1775
clang::VarDecl::Create
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2051
clang::AdjustedType
Represents a type which was implicitly adjusted by the semantic engine for arbitrary reasons.
Definition: Type.h:2684
clang::SourceManager::getDecomposedLoc
std::pair< FileID, unsigned > getDecomposedLoc(SourceLocation Loc) const
Decompose the specified location into a raw FileID + Offset pair.
Definition: SourceManager.h:1236
clang::TemplateParameterList::getTemplateLoc
SourceLocation getTemplateLoc() const
Definition: DeclTemplate.h:193
clang::CXXScopeSpec::getWithLocInContext
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: DeclSpec.cpp:151
clang::TypeLocBuilder
Definition: TypeLocBuilder.h:22
clang::CastExpr::getCastKind
CastKind getCastKind() const
Definition: Expr.h:3576
clang::Decl::isImplicit
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:557
clang::Qualifiers::OCL_Autoreleasing
@ OCL_Autoreleasing
Assigning into this object requires a lifetime extension.
Definition: Type.h:181
clang::DeclaratorChunk::ParamInfo::Param
Decl * Param
Definition: DeclSpec.h:1254
clang::MemberExpr::getMemberDecl
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition: Expr.h:3303
clang::Decl::getOwningModule
Module * getOwningModule() const
Get the module that owns this declaration (for visibility purposes).
Definition: DeclBase.h:781
clang::ASTContext::ShortTy
CanQualType ShortTy
Definition: ASTContext.h:1101
clang::Sema::AMK_OptionalProtocolImplementation
@ AMK_OptionalProtocolImplementation
Merge availability attributes for an implementation of an optional protocol requirement.
Definition: Sema.h:3650
clang::NamedDecl::getFormalLinkage
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.h:397
clang::Sema::PopExpressionEvaluationContext
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17300
clang::FunctionDefinitionKind::Declaration
@ Declaration
clang::Decl::dropAttr
void dropAttr()
Definition: DeclBase.h:512
clang::IncompleteArrayType
Represents a C array with an unspecified size.
Definition: Type.h:3004
clang::ASTContext::getFunctionNoProtoType
QualType getFunctionNoProtoType(QualType ResultTy, const FunctionType::ExtInfo &Info) const
Return a K&R style C function type like 'int()'.
Definition: ASTContext.cpp:4252
clang::DecompositionDeclarator::getSourceRange
SourceRange getSourceRange() const
Definition: DeclSpec.h:1747
clang::CXXDestructorDecl::Create
static CXXDestructorDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, bool isImplicitlyDeclared, ConstexprSpecKind ConstexprKind, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2738
clang::Qualifiers::ObjCLifetime
ObjCLifetime
Definition: Type.h:162
clang::RecordDecl::setAnonymousStructOrUnion
void setAnonymousStructOrUnion(bool Anon)
Definition: Decl.h:3962
clang::Sema::LookupNameKind
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:4301
clang::DeclRefExpr::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Expr.cpp:515
clang::ASTContext::setManglingNumber
void setManglingNumber(const NamedDecl *ND, unsigned Number)
Definition: ASTContext.cpp:11790
clang::Decl::IDNS_Ordinary
@ IDNS_Ordinary
Ordinary names.
Definition: DeclBase.h:141
clang::SC_Static
@ SC_Static
Definition: Specifiers.h:237
clang::Declarator::SetIdentifier
void SetIdentifier(IdentifierInfo *Id, SourceLocation IdLoc)
Set the name of this declarator to be the given identifier.
Definition: DeclSpec.h:2197
TranslateIvarVisibility
static ObjCIvarDecl::AccessControl TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility)
TranslateIvarVisibility - Translate visibility from a token ID to an AST enum value.
Definition: SemaDecl.cpp:17403
clang::AttributedTypeLoc::getModifiedLoc
TypeLoc getModifiedLoc() const
The modified type, which is generally canonically different from the attribute type.
Definition: TypeLoc.h:877
clang::sema::CapturingScopeInfo::ImpCap_LambdaByval
@ ImpCap_LambdaByval
Definition: ScopeInfo.h:666
clang::TemplateDecl::getTemplateParameters
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:419
clang::APIntStorage::getValue
llvm::APInt getValue() const
Definition: Expr.h:1478
clang::Sema::ActOnUninitializedDecl
void ActOnUninitializedDecl(Decl *dcl)
Definition: SemaDecl.cpp:12883
clang::Sema::ActOnInitializerError
void ActOnInitializerError(Decl *Dcl)
ActOnInitializerError - Given that there was an error parsing an initializer for the given declaratio...
Definition: SemaDecl.cpp:12841
clang::ASTContext::UnsignedLongLongTy
CanQualType UnsignedLongLongTy
Definition: ASTContext.h:1103
clang::ETK_None
@ ETK_None
No keyword precedes the qualified type name.
Definition: Type.h:5426
clang::Sema::ConvertDeclToDeclGroup
DeclGroupPtrTy ConvertDeclToDeclGroup(Decl *Ptr, Decl *OwnedType=nullptr)
Definition: SemaDecl.cpp:56
clang::QualType::getUnqualifiedType
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6582
clang::Type::isObjCLifetimeType
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4344
clang::FunctionDecl::setHasImplicitReturnZero
void setHasImplicitReturnZero(bool IRZ)
State that falling off this function implicitly returns null/zero.
Definition: Decl.h:2248
clang::Module::Parent
Module * Parent
The parent of this module.
Definition: Module.h:133
CharUnits.h
clang::DeclarationNameInfo::getName
DeclarationName getName() const
getName - Returns the embedded declaration name.
Definition: DeclarationName.h:779
clang::ASTContext::hasSameFunctionTypeIgnoringPtrSizes
bool hasSameFunctionTypeIgnoringPtrSizes(QualType T, QualType U)
Determine whether two function types are the same, ignoring pointer sizes in the return type and para...
Definition: ASTContext.cpp:3206
clang::CC_C
@ CC_C
Definition: Specifiers.h:264
clang::QualType::PCK_Trivial
@ PCK_Trivial
The type does not fall into any of the following categories.
Definition: Type.h:1167
clang::Sema::PushLambdaScope
sema::LambdaScopeInfo * PushLambdaScope()
Definition: Sema.cpp:2194
clang::Type::isObjCObjectPointerType
bool isObjCObjectPointerType() const
Definition: Type.h:6878
clang::LookupResult::Filter::hasNext
bool hasNext() const
Definition: Lookup.h:639
clang::FunctionType::ExtInfo::withRegParm
ExtInfo withRegParm(unsigned RegParm) const
Definition: Type.h:3781
clang::ObjCCategoryDecl
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2273
clang::FunctionDecl::hasBody
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:2972
clang::Sema::CorrectTypo
TypoCorrection CorrectTypo(const DeclarationNameInfo &Typo, Sema::LookupNameKind LookupKind, Scope *S, CXXScopeSpec *SS, CorrectionCandidateCallback &CCC, CorrectTypoKind Mode, DeclContext *MemberContext=nullptr, bool EnteringContext=false, const ObjCObjectPointerType *OPT=nullptr, bool RecordFailure=true)
Try to "correct" a typo in the source code by finding visible declarations whose names are similar to...
Definition: SemaLookup.cpp:5101
clang::Visibility
Visibility
Describes the different kinds of visibility that a declaration may have.
Definition: Visibility.h:33
clang::TemplateParameterList::getRAngleLoc
SourceLocation getRAngleLoc() const
Definition: DeclTemplate.h:195
clang::Type::isFunctionProtoType
bool isFunctionProtoType() const
Definition: Type.h:2021
clang::Sema::SkipBodyInfo::CheckSameAsPrevious
bool CheckSameAsPrevious
Definition: Sema.h:2685
clang::InitializationKind::CreateDefault
static InitializationKind CreateDefault(SourceLocation InitLoc)
Create a default initialization.
Definition: Initialization.h:682
ShadowedDeclKind
ShadowedDeclKind
Enum describing the select options in diag::warn_decl_shadow.
Definition: SemaDecl.cpp:7767
clang::ParsedAttributesView::empty
bool empty() const
Definition: ParsedAttr.h:915
isTagTypeWithMissingTag
static bool isTagTypeWithMissingTag(Sema &SemaRef, LookupResult &Result, Scope *S, CXXScopeSpec &SS, IdentifierInfo *&Name, SourceLocation NameLoc)
Definition: SemaDecl.cpp:810
clang::Sema::CheckDeductionGuideDeclarator
void CheckDeductionGuideDeclarator(Declarator &D, QualType &R, StorageClass &SC)
Check the validity of a declarator that we parsed for a deduction-guide.
Definition: SemaDeclCXX.cpp:10970
clang::VarDecl::getDescribedVarTemplate
VarTemplateDecl * getDescribedVarTemplate() const
Retrieves the variable template that is described by this variable declaration.
Definition: Decl.cpp:2678
clang::DeducedType::isDeduced
bool isDeduced() const
Definition: Type.h:5038
clang::ASTContext::UnsignedCharTy
CanQualType UnsignedCharTy
Definition: ASTContext.h:1102
clang::Sema::ActOnFinishKNRParamDeclarations
void ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D, SourceLocation LocAfterDecls)
Definition: SemaDecl.cpp:14202
clang::OpaquePtr
Wrapper for void* pointer.
Definition: Ownership.h:50
clang::Declarator::setRedeclaration
void setRedeclaration(bool Val)
Definition: DeclSpec.h:2601
clang::DeducedType::getDeducedType
QualType getDeducedType() const
Get the type deduced for this placeholder type, or null if it has not been deduced.
Definition: Type.h:5037
RemoveUsingDecls
static void RemoveUsingDecls(LookupResult &R)
Removes using shadow declarations from the lookup results.
Definition: SemaDecl.cpp:1706
clang::DeclarationName::CXXConversionFunctionName
@ CXXConversionFunctionName
Definition: DeclarationName.h:206
clang::DeclSpec::TST_int
static const TST TST_int
Definition: DeclSpec.h:267
clang::FunctionProtoType::ExtProtoInfo::withExceptionSpec
ExtProtoInfo withExceptionSpec(const ExceptionSpecInfo &ESI)
Definition: Type.h:3998
CheckAnonMemberRedeclaration
static bool CheckAnonMemberRedeclaration(Sema &SemaRef, Scope *S, DeclContext *Owner, DeclarationName Name, SourceLocation NameLoc, bool IsUnion)
We are trying to inject an anonymous member into the given scope; check if there's an existing declar...
Definition: SemaDecl.cpp:5047
clang::TemplateIdAnnotation::LAngleLoc
SourceLocation LAngleLoc
The location of the '<' before the template argument list.
Definition: ParsedTemplate.h:178
clang::LangAS
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
clang::VarDecl::isThisDeclarationADemotedDefinition
bool isThisDeclarationADemotedDefinition() const
If this definition should pretend to be a declaration.
Definition: Decl.h:1385
clang::DeclSpec::getStorageClassSpecLoc
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:449
clang::FunctionDecl::isGlobal
bool isGlobal() const
Determines whether this is a global function.
Definition: Decl.cpp:3253
clang::supportsVariadicCall
bool supportsVariadicCall(CallingConv CC)
Checks whether the given calling convention supports variadic calls.
Definition: Specifiers.h:287
clang::Sema::isAcceptableTagRedeclaration
bool isAcceptableTagRedeclaration(const TagDecl *Previous, TagTypeKind NewTag, bool isDefinition, SourceLocation NewTagLoc, const IdentifierInfo *Name)
Determine whether a tag with a given kind is acceptable as a redeclaration of the given tag declarati...
Definition: SemaDecl.cpp:15643
clang::sema::FunctionScopeInfo
Retains information about a function, method, or block that is currently being parsed.
Definition: ScopeInfo.h:97
clang::Sema::AbstractReturnType
@ AbstractReturnType
Definition: Sema.h:7801
clang::isDiscardableGVALinkage
bool isDiscardableGVALinkage(GVALinkage L)
Definition: Linkage.h:81
clang::ParsedAttributesView::Range
SourceRange Range
Definition: ParsedAttr.h:914
clang::Sema::DiagnoseShadowingLambdaDecls
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:7967
clang::Sema::HandleField
FieldDecl * HandleField(Scope *S, RecordDecl *TagD, SourceLocation DeclStart, Declarator &D, Expr *BitfieldWidth, InClassInitStyle InitStyle, AccessSpecifier AS)
HandleField - Analyze a field of a C struct or a C++ data member.
Definition: SemaDecl.cpp:17044
ShouldWarnAboutMissingPrototype
static bool ShouldWarnAboutMissingPrototype(const FunctionDecl *FD, const FunctionDecl *&PossiblePrototype)
Definition: SemaDecl.cpp:14273
clang::Sema::ActOnObjCContainerStartDefinition
Decl * ActOnObjCContainerStartDefinition(Decl *IDecl)
Definition: SemaDecl.cpp:16793
clang::Sema::diagnoseTypo
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
Definition: SemaLookup.cpp:5398
clang::Type::castAs
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7330
clang::Sema::canDelayFunctionBody
bool canDelayFunctionBody(const Declarator &D)
Determine whether we can delay parsing the body of a function or function template until it is used,...
Definition: SemaDecl.cpp:14622
clang::Sema::FinalizeDeclaratorGroup
DeclGroupPtrTy FinalizeDeclaratorGroup(Scope *S, const DeclSpec &DS, ArrayRef< Decl * > Group)
Definition: SemaDecl.cpp:13765
clang::Sema::TemplateNameKindForDiagnostics
TemplateNameKindForDiagnostics
Describes the detailed kind of a template name. Used in diagnostics.
Definition: Sema.h:2923
clang::ConstexprSpecKind
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition: Specifiers.h:32
clang::TargetInfo::getTriple
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1160
clang::AccessSpecifier
AccessSpecifier
A C++ access specifier (public, private, protected), plus the special value "none" which means differ...
Definition: Specifiers.h:108
clang::ASTContext::UnsignedLongTy
CanQualType UnsignedLongTy
Definition: ASTContext.h:1102
clang::Sema::shouldLinkDependentDeclWithPrevious
bool shouldLinkDependentDeclWithPrevious(Decl *D, Decl *OldDecl)
Checks if the new declaration declared in dependent context must be put in the same redeclaration cha...
Definition: SemaDecl.cpp:10360
clang::DependentNameTypeLoc::setQualifierLoc
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2337
clang::Decl::isInIdentifierNamespace
bool isInIdentifierNamespace(unsigned NS) const
Definition: DeclBase.h:826
clang::VarDecl::ListInit
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:886
clang::MemberExpr::getBase
Expr * getBase() const
Definition: Expr.h:3297
clang::Sema::LazilyCreateBuiltin
NamedDecl * LazilyCreateBuiltin(IdentifierInfo *II, unsigned ID, Scope *S, bool ForRedeclaration, SourceLocation Loc)
LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
Definition: SemaDecl.cpp:2236
clang::InitializationSequence::Perform
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Definition: SemaInit.cpp:7988
clang::Sema::MarkTypoCorrectedFunctionDefinition
void MarkTypoCorrectedFunctionDefinition(const NamedDecl *F)
Definition: SemaDecl.cpp:8522
StorageClassSpecToVarDeclStorageClass
static StorageClass StorageClassSpecToVarDeclStorageClass(const DeclSpec &DS)
StorageClassSpecToVarDeclStorageClass - Maps a DeclSpec::SCS to a VarDecl::StorageClass.
Definition: SemaDecl.cpp:5150
clang::ArrayTypeLoc::getRBracketLoc
SourceLocation getRBracketLoc() const
Definition: TypeLoc.h:1529
clang::TemplateArgumentListInfo::arguments
llvm::ArrayRef< TemplateArgumentLoc > arguments() const
Definition: TemplateBase.h:591
clang::isWhitespace
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition: CharInfo.h:93
clang::DecompositionDeclarator::getLSquareLoc
SourceLocation getLSquareLoc() const
Definition: DeclSpec.h:1745
clang::CXXRecordDecl
Represents a C++ struct/union/class.
Definition: DeclCXX.h:254
clang::CXXMethodDecl::getMethodQualifiers
Qualifiers getMethodQualifiers() const
Definition: DeclCXX.h:2113
clang::ArrayTypeLoc::getSizeExpr
Expr * getSizeExpr() const
Definition: TypeLoc.h:1541
clang::FunctionDecl::getNameInfo
DeclarationNameInfo getNameInfo() const
Definition: Decl.h:2050
clang::ObjCMethodDecl::param_iterator
ParmVarDecl *const * param_iterator
Definition: DeclObjC.h:353
clang::Type::isImageType
bool isImageType() const
Definition: Type.h:6971
CreateNewFunctionDecl
static FunctionDecl * CreateNewFunctionDecl(Sema &SemaRef, Declarator &D, DeclContext *DC, QualType &R, TypeSourceInfo *TInfo, StorageClass SC, bool &IsVirtualOkay)
Definition: SemaDecl.cpp:8722
clang::Sema::DeviceDiagnosticReason::All
@ All
A flag representing 'all'.
clang::FunctionDecl::setPreviousDeclaration
void setPreviousDeclaration(FunctionDecl *PrevDecl)
Definition: Decl.cpp:3313
clang::sema::AnalysisBasedWarnings::Policy
Definition: AnalysisBasedWarnings.h:33
clang::FunctionType::ExtInfo::getHasRegParm
bool getHasRegParm() const
Definition: Type.h:3725
clang::UnqualifiedIdKind::IK_TemplateId
@ IK_TemplateId
A template-id, e.g., f<int>.
clang::VarDecl::isThisDeclarationADefinition
DefinitionKind isThisDeclarationADefinition(ASTContext &) const
Check whether this declaration is a definition.
Definition: Decl.cpp:2161
clang::Sema::getNonTagTypeDeclKind
NonTagKind getNonTagTypeDeclKind(const Decl *D, TagTypeKind TTK)
Given a non-tag type declaration, returns an enum useful for indicating what kind of non-tag type thi...
Definition: SemaDecl.cpp:15614
clang::Type::getAsUnionType
const RecordType * getAsUnionType() const
NOTE: getAs*ArrayType are methods on ASTContext.
Definition: Type.cpp:660
clang::LabelDecl::getStmt
LabelStmt * getStmt() const
Definition: Decl.h:519
clang::tok::TokenKind
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition: TokenKinds.h:25
clang::Type::isUnionType
bool isUnionType() const
Definition: Type.cpp:595
clang::DeclContext::getRedeclContext
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1792
clang::ASTContext::adjustFunctionType
const FunctionType * adjustFunctionType(const FunctionType *Fn, FunctionType::ExtInfo EInfo)
Change the ExtInfo on a function type.
Definition: ASTContext.cpp:3115
clang::ASTContext::LongLongTy
CanQualType LongLongTy
Definition: ASTContext.h:1101
clang::ast_matchers::decl
const internal::VariadicAllOfMatcher< Decl > decl
Matches declarations.
Definition: ASTMatchersInternal.cpp:734
clang::Declarator::getCXXScopeSpec
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:1925
P
StringRef P
Definition: ASTMatchersInternal.cpp:563
clang::Sema::CTK_ErrorRecovery
@ CTK_ErrorRecovery
Definition: Sema.h:4544
isUsingDecl
static bool isUsingDecl(NamedDecl *D)
Definition: SemaDecl.cpp:1699
clang::Attr::isInherited
bool isInherited() const
Definition: Attr.h:93
clang::Type::isDependentType
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2183
clang::Type::isInstantiationDependentType
bool isInstantiationDependentType() const
Determine whether this type is an instantiation-dependent type, meaning that the type involves a temp...
Definition: Type.h:2191
clang::VK_PRValue
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition: Specifiers.h:120
clang::TypedefNameDecl::getAnonDeclWithTypedefName
TagDecl * getAnonDeclWithTypedefName(bool AnyRedecl=false) const
Retrieves the tag declaration for which this is the typedef name for linkage purposes,...
Definition: Decl.cpp:5027
clang::FunctionType::getNameForCallConv
static StringRef getNameForCallConv(CallingConv CC)
Definition: Type.cpp:3162
clang::Sema::ActOnVariableDeclarator
NamedDecl * ActOnVariableDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope, ArrayRef< BindingDecl * > Bindings=None)
Definition: SemaDecl.cpp:7081
clang::sema::FunctionScopeInfo::ObjCWarnForNoInitDelegation
bool ObjCWarnForNoInitDelegation
This starts true for a secondary initializer method and will be set to false if there is an invocatio...
Definition: ScopeInfo.h:160
clang::QualType::isCanonical
bool isCanonical() const
Definition: Type.h:6546
clang::Attr::clone
Attr * clone(ASTContext &C) const
clang::AttributeCommonInfo::getRange
SourceRange getRange() const
Definition: AttributeCommonInfo.h:130
clang::LCD_ByRef
@ LCD_ByRef
Definition: Lambda.h:25
clang::TypeWithKeyword::getTagTypeKindForTypeSpec
static TagTypeKind getTagTypeKindForTypeSpec(unsigned TypeSpec)
Converts a type specifier (DeclSpec::TST) into a tag type kind.
Definition: Type.cpp:2833
clang::LookupResult::suppressDiagnostics
void suppressDiagnostics()
Suppress the diagnostics that would normally fire because of this lookup.
Definition: Lookup.h:583
clang::ASTContext::UnsignedIntTy
CanQualType UnsignedIntTy
Definition: ASTContext.h:1102
clang::Type::getContainedAutoType
AutoType * getContainedAutoType() const
Get the AutoType whose type will be deduced for a variable with an initializer of this type.
Definition: Type.h:2288
clang::TagDecl::startDefinition
void startDefinition()
Starts the definition of this tag declaration.
Definition: Decl.cpp:4342
clang::attr::Kind
Kind
Definition: AttrKinds.h:22
clang::Decl::getPreviousDecl
Decl * getPreviousDecl()
Retrieve the previous declaration that declares the same entity as this declaration,...
Definition: DeclBase.h:992
clang::VariableArrayType
Represents a C array with a specified size that is not an integer-constant-expression.
Definition: Type.h:3048
clang::FunctionTemplateSpecializationInfo
Provides information about a function template specialization, which is a FunctionDecl that has been ...
Definition: DeclTemplate.h:468
clang::Decl::getFriendObjectKind
FriendObjectKind getFriendObjectKind() const
Determines whether this declaration is the object of a friend declaration and, if so,...
Definition: DeclBase.h:1151
clang::sema::CapturingScopeInfo::Captures
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:683
clang::LookupResult::empty
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:339
clang::FieldDecl::isBitField
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:2917
clang::Type::canDecayToPointerType
bool canDecayToPointerType() const
Determines whether this type can decay to a pointer type.
Definition: Type.h:7200
clang::Sema::mergeErrorAttr
ErrorAttr * mergeErrorAttr(Decl *D, const AttributeCommonInfo &CI, StringRef NewUserDiagnostic)
clang::Type::isPointerType
bool isPointerType() const
Definition: Type.h:6750
clang::EnumDecl::isScoped
bool isScoped() const
Returns true if this is a C++11 scoped enumeration.
Definition: Decl.h:3812
clang::Sema::getScopeForDeclContext
static Scope * getScopeForDeclContext(Scope *S, DeclContext *DC)
Finds the scope corresponding to the given decl context, if it happens to be an enclosing scope.
Definition: SemaDecl.cpp:1561
clang::Decl::hasAttrs
bool hasAttrs() const
Definition: DeclBase.h:483
clang::Declarator::getFunctionTypeInfo
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2329
clang::FunctionType::ExtInfo::withNoCallerSavedRegs
ExtInfo withNoCallerSavedRegs(bool noCallerSavedRegs) const
Definition: Type.h:3767
clang::Scope::TemplateParamScope
@ TemplateParamScope
This is a scope that corresponds to the template parameters of a C++ template.
Definition: Scope.h:77
clang::LookupResult::AmbiguousTagHiding
@ AmbiguousTagHiding
Name lookup results in an ambiguity because an entity with a tag name was hidden by an entity with an...
Definition: Lookup.h:135
CheckConvertedConstantExpression
static ExprResult CheckConvertedConstantExpression(Sema &S, Expr *From, QualType T, APValue &Value, Sema::CCEKind CCE, bool RequireInt, NamedDecl *Dest)
CheckConvertedConstantExpression - Check that the expression From is a converted constant expression ...
Definition: SemaOverload.cpp:5692
clang::Builtin::Context::isConst
bool isConst(unsigned ID) const
Return true if this function has no side effects and doesn't read memory.
Definition: Builtins.h:107
isRepresentableIntegerValue
static bool isRepresentableIntegerValue(ASTContext &Context, llvm::APSInt &Value, QualType T)
Determine whether the given integral value is representable within the given type T.
Definition: SemaDecl.cpp:18018
clang::TypeLoc::getAsAdjusted
T getAsAdjusted() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:2608
clang::DeclaratorChunk::Function
@ Function
Definition: DeclSpec.h:1177
isOpenCLSizeDependentType
static bool isOpenCLSizeDependentType(ASTContext &C, QualType Ty)
Definition: SemaDecl.cpp:8893
clang::NamedDecl::hasExternalFormalLinkage
bool hasExternalFormalLinkage() const
True if this decl has external linkage.
Definition: Decl.h:402
clang::TypedefType::getDecl
TypedefNameDecl * getDecl() const
Definition: Type.h:4417
getRedeclDiagFromTagKind
static unsigned getRedeclDiagFromTagKind(TagTypeKind Tag)
Get diagnostic select index for tag kind for redeclaration diagnostic message.
Definition: SemaDecl.cpp:15596
clang::DeclSpec::isDeclRep
static bool isDeclRep(TST T)
Definition: DeclSpec.h:416
clang::TypedefNameDecl::setTypeSourceInfo
void setTypeSourceInfo(TypeSourceInfo *newType)
Definition: Decl.h:3246
clang::TagDecl::isBeingDefined
bool isBeingDefined() const
Return true if this decl is currently being defined.
Definition: Decl.h:3457
clang::CXXRecordDecl::hasNonTrivialCopyConstructor
bool hasNonTrivialCopyConstructor() const
Determine whether this class has a non-trivial copy constructor (C++ [class.copy]p6,...
Definition: DeclCXX.h:1243
clang::ASTContext::getDeclAlign
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
Definition: ASTContext.cpp:1732
clang::TypeLoc::getUnqualifiedLoc
UnqualTypeLoc getUnqualifiedLoc() const
Skips past any qualifiers, if this is qualified.
Definition: TypeLoc.h:326
clang::FunctionType::ExtInfo::getCC
CallingConv getCC() const
Definition: Type.h:3734
clang::ActionResult::get
PtrTy get() const
Definition: Ownership.h:169
clang::LCK_ByRef
@ LCK_ByRef
Capturing by reference.
Definition: Lambda.h:37
clang::NamedDecl::getIdentifier
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:268
clang::ClassTemplateDecl
Declaration of a class template.
Definition: DeclTemplate.h:2247
clang::ValueDecl
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:675
clang::FunctionDecl::setTrivial
void setTrivial(bool IT)
Definition: Decl.h:2208
clang::TNK_Type_template
@ TNK_Type_template
The name refers to a template whose specialization produces a type.
Definition: TemplateKinds.h:30
clang::AS_protected
@ AS_protected
Definition: Specifiers.h:110
clang::ASTContext::IntTy
CanQualType IntTy
Definition: ASTContext.h:1101
clang::RecordDecl::completeDefinition
virtual void completeDefinition()
Note that the definition of this type is now complete.
Definition: Decl.cpp:4648
clang::ASTContext::addModuleInitializer
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
Definition: ASTContext.cpp:1157
clang::Sema::ActOnObjCTemporaryExitContainerContext
void ActOnObjCTemporaryExitContainerContext(DeclContext *DC)
Invoked when we must temporarily exit the objective-c container scope for parsing/looking-up C constr...
Definition: SemaDecl.cpp:16908
clang::ASTContext::GE_Missing_stdio
@ GE_Missing_stdio
Missing a type from <stdio.h>
Definition: ASTContext.h:2201
mergeParamDeclAttributes
static void mergeParamDeclAttributes(ParmVarDecl *newDecl, const ParmVarDecl *oldDecl, Sema &S)
mergeParamDeclAttributes - Copy attributes from the old parameter to the new one.
Definition: SemaDecl.cpp:3178
GenerateFixForUnusedDecl
static void GenerateFixForUnusedDecl(const NamedDecl *D, ASTContext &Ctx, FixItHint &Hint)
Definition: SemaDecl.cpp:1948
clang::DeclSpec::isModulePrivateSpecified
bool isModulePrivateSpecified() const
Definition: DeclSpec.h:751
clang::DeclaratorChunk::Kind
enum clang::DeclaratorChunk::@210 Kind
clang::ASTContext::PSF_Implicit
@ PSF_Implicit
Definition: ASTContext.h:3266
clang::LangOptions::NonGC
@ NonGC
Definition: LangOptions.h:63
clang::FunctionDecl::getLanguageLinkage
LanguageLinkage getLanguageLinkage() const
Compute the language linkage.
Definition: Decl.cpp:3235
clang::TypedefType::desugar
QualType desugar() const
Definition: Type.cpp:3423
clang::CXXLanguageLinkage
@ CXXLanguageLinkage
Definition: Linkage.h:66
clang::TemplateName
Represents a C++ template name within the type system.
Definition: TemplateName.h:190
clang::VarDecl::getStorageClass
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1084
clang::BinaryOperator::getLHS
Expr * getLHS() const
Definition: Expr.h:3910
clang::Sema::RedeclarationKind
RedeclarationKind
Specifies whether (or how) name lookup is being performed for a redeclaration (vs.
Definition: Sema.h:4355
clang::FunctionDecl::setImplicitlyInline
void setImplicitlyInline(bool I=true)
Flag that this function is implicitly inline.
Definition: Decl.h:2612
clang::CXXScopeSpec::location_data
char * location_data() const
Retrieve the data associated with the source-location information.
Definition: DeclSpec.h:218
clang::CXXRecordDecl::hasTrivialDefaultConstructor
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition: DeclCXX.h:1195
clang::VarDecl::isLocalVarDeclOrParm
bool isLocalVarDeclOrParm() const
Similar to isLocalVarDecl but also includes parameters.
Definition: Decl.h:1178
clang::CharUnits::isZero
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:116
getCanonicalDecl
static const Decl * getCanonicalDecl(const Decl *D)
Definition: IndexingContext.cpp:301
clang::DeclContext::addDecl
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1571
clang::ASTContext::getTagDeclType
QualType getTagDeclType(const TagDecl *Decl) const
Return the unique reference to the type for the specified TagDecl (struct/union/class/enum) decl.
Definition: ASTContext.cpp:5817
clang::Builtin::Context::isConstWithoutErrno
bool isConstWithoutErrno(unsigned ID) const
Return true if this function has no side effects and doesn't read memory, except for possibly errno.
Definition: Builtins.h:210
clang::FunctionProtoType
Represents a prototype with parameter type info, e.g.
Definition: Type.h:3900
clang::Sema::AlignPackInfo::IsAlignAttr
bool IsAlignAttr() const
Definition: Sema.h:718
clang::DeclSpec::isMissingDeclaratorOk
bool isMissingDeclaratorOk()
Checks if this DeclSpec can stand alone, without a Declarator.
Definition: DeclSpec.cpp:1444
clang::ASTContext::Idents
IdentifierTable & Idents
Definition: ASTContext.h:651
clang::Sema::CheckShadowingDeclModification
void CheckShadowingDeclModification(Expr *E, SourceLocation Loc)
Warn if 'E', which is an expression that is about to be modified, refers to a shadowing declaration.
Definition: SemaDecl.cpp:7999
clang::Sema::inferObjCARCLifetime
bool inferObjCARCLifetime(ValueDecl *decl)
Definition: SemaDecl.cpp:6540
clang::FunctionDecl::isMultiVersion
bool isMultiVersion() const
True if this function is considered a multiversioned function.
Definition: Decl.h:2435
clang::Declarator::getInventedTemplateParameterList
TemplateParameterList * getInventedTemplateParameterList() const
The template parameter list generated from the explicit template parameters along with any invented t...
Definition: DeclSpec.h:2503
clang::DeclContext::getParent
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1872
clang::Sema::shouldIgnoreInHostDeviceCheck
bool shouldIgnoreInHostDeviceCheck(FunctionDecl *Callee)
Definition: SemaDecl.cpp:18931
clang::CLanguageLinkage
@ CLanguageLinkage
Definition: Linkage.h:65
clang::Expr::getExprLoc
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition: Expr.cpp:246
clang::QualType::isConstant
bool isConstant(const ASTContext &Ctx) const
Definition: Type.h:810
clang::Type::isIncompleteArrayType
bool isIncompleteArrayType() const
Definition: Type.h:6824
Specifier
const NestedNameSpecifier * Specifier
Definition: USRLocFinder.cpp:173
clang::MultiVersionKind::None
@ None
clang::ASTContext::getPrintingPolicy
const clang::PrintingPolicy & getPrintingPolicy() const
Definition: ASTContext.h:704
clang::RecordDecl::fields
field_range fields() const
Definition: Decl.h:4105
clang::TypeLoc::getAs
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition: TypeLoc.h:88
FixInvalidVariablyModifiedTypeLoc
static void FixInvalidVariablyModifiedTypeLoc(TypeLoc SrcTL, TypeLoc DstTL)
Definition: SemaDecl.cpp:6233
clang::TypeDecl::setTypeForDecl
void setTypeForDecl(const Type *TD)
Definition: Decl.h:3167
clang::ElaboratedTypeLoc::setElaboratedKeywordLoc
void setElaboratedKeywordLoc(SourceLocation Loc)
Definition: TypeLoc.h:2269
clang::TypedefDecl::Create
static TypedefDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, TypeSourceInfo *TInfo)
Definition: Decl.cpp:5019
clang::TemplateDecl
The base class of all kinds of template declarations (e.g., class, function, etc.).
Definition: DeclTemplate.h:400
checkDLLAttributeRedeclaration
static void checkDLLAttributeRedeclaration(Sema &S, NamedDecl *OldDecl, NamedDecl *NewDecl, bool IsSpecialization, bool IsDefinition)
Definition: SemaDecl.cpp:6717
clang::LookupResult::Filter::done
void done()
Definition: Lookup.h:672
CheckMultiVersionValue
static bool CheckMultiVersionValue(Sema &S, const FunctionDecl *FD)
Check the target attribute of the function for MultiVersion validity.
Definition: SemaDecl.cpp:10391
clang::MangleNumberingContext::getStaticLocalNumber
virtual unsigned getStaticLocalNumber(const VarDecl *VD)=0
Static locals are numbered by source order.
clang::ASTContext::GE_Missing_type
@ GE_Missing_type
Missing a type.
Definition: ASTContext.h:2198
clang::VarDecl::getDefinition
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition: Decl.cpp:2267
clang::VarDecl::getActingDefinition
VarDecl * getActingDefinition()
Get the tentative definition that acts as the real definition in a TU.
Definition: Decl.cpp:2246
clang::QualType::isNull
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:740
clang::Sema::ActOnFinishDelayedAttribute
void ActOnFinishDelayedAttribute(Scope *S, Decl *D, ParsedAttributes &Attrs)
ActOnFinishDelayedAttribute - Invoked when we have finished parsing an attribute for which parsing is...
Definition: SemaDecl.cpp:15103
llvm::ArrayRef
Definition: LLVM.h:34
clang::DeclSpec::TST_typename
static const TST TST_typename
Definition: DeclSpec.h:288
clang::Builtin::Context::getName
const char * getName(unsigned ID) const
Return the identifier name for the specified builtin, e.g.
Definition: Builtins.h:86
clang::Sema::setTagNameForLinkagePurposes
void setTagNameForLinkagePurposes(TagDecl *TagFromDeclSpec, TypedefNameDecl *NewTD)
Definition: SemaDecl.cpp:4696
Lexer.h
clang::LangAS::opencl_global
@ opencl_global
Value
Value
Definition: UninitializedValues.cpp:102
clang::Decl
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:83
clang::AttributeCommonInfo
Definition: AttributeCommonInfo.h:22
clang::Type::isClkEventT
bool isClkEventT() const
Definition: Type.h:6959
Scope.h
clang::ParmVarDecl::getFunctionScopeIndex
unsigned getFunctionScopeIndex() const
Returns the index of this parameter in its prototype or method scope.
Definition: Decl.h:1724
clang::Declarator::isFunctionDefinition
bool isFunctionDefinition() const
Definition: DeclSpec.h:2576
clang::DeclaratorDecl
Represents a ValueDecl that came out of a declarator.
Definition: Decl.h:727
clang::FunctionDecl::isPure
bool isPure() const
Whether this virtual function is pure, i.e.
Definition: Decl.h:2190
clang::TypeLoc
Base wrapper for a particular "section" of type source info.
Definition: TypeLoc.h:58
clang::Expr::IgnoreParenImpCasts
Expr * IgnoreParenImpCasts() LLVM_READONLY
Skip past any parentheses and implicit casts which might surround this expression until reaching a fi...
Definition: Expr.cpp:2948
clang::ASTContext::LongTy
CanQualType LongTy
Definition: ASTContext.h:1101
clang::Sema::CheckDestructorDeclarator
QualType CheckDestructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckDestructorDeclarator - Called by ActOnDeclarator to check the well-formednes of the destructor d...
Definition: SemaDeclCXX.cpp:10606
HeaderSearch.h
clang::Sema::findLocallyScopedExternCDecl
NamedDecl * findLocallyScopedExternCDecl(DeclarationName Name)
Look for a locally scoped extern "C" declaration by the given name.
Definition: SemaDecl.cpp:6326
clang::DeclGroupRef
Definition: DeclGroup.h:51
clang::DeclSpec::TST_typeofType
static const TST TST_typeofType
Definition: DeclSpec.h:289
clang::DeclarationNameInfo::setNamedTypeInfo
void setNamedTypeInfo(TypeSourceInfo *TInfo)
setNamedTypeInfo - Sets the source type info associated to the name.
Definition: DeclarationName.h:805
clang::Sema::ActOnTypedefDeclarator
NamedDecl * ActOnTypedefDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous)
Definition: SemaDecl.cpp:6351
clang::FunctionDecl::isReplaceableGlobalAllocationFunction
bool isReplaceableGlobalAllocationFunction(Optional< unsigned > *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions: void *operato...
Definition: Decl.cpp:3142
clang::DeclSpec::getInlineSpecLoc
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:570
clang::Sema::ActOnDeclarator
Decl * ActOnDeclarator(Scope *S, Declarator &D)
Definition: SemaDecl.cpp:5799
clang::Sema::Consumer
ASTConsumer & Consumer
Definition: Sema.h:588
clang::LCK_StarThis
@ LCK_StarThis
Capturing the *this object by copy.
Definition: Lambda.h:35
clang::QualType::isObjCGCWeak
bool isObjCGCWeak() const
true when Type is objc's weak.
Definition: Type.h:1112
clang::LanguageLinkage
LanguageLinkage
Describes the different kinds of language linkage (C++ [dcl.link]) that an entity may have.
Definition: Linkage.h:64
clang::Module::PrivateModuleFragment
@ PrivateModuleFragment
This is the private module fragment within some C++ module.
Definition: Module.h:125
clang::Sema
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:531
clang::FunctionDecl::TK_NonTemplate
@ TK_NonTemplate
Definition: Decl.h:1865
clang::ActionResult::isInvalid
bool isInvalid() const
Definition: Ownership.h:165
clang::DeclSpec::SCS_private_extern
@ SCS_private_extern
Definition: DeclSpec.h:240
clang::UnqualifiedIdKind::IK_DestructorName
@ IK_DestructorName
A destructor name.
clang::Decl::FOK_Declared
@ FOK_Declared
A friend of a previously-declared entity.
Definition: DeclBase.h:1143
clang::VarDecl::setInitStyle
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1361
clang::QualType::isPODType
bool isPODType(const ASTContext &Context) const
Determine whether this is a Plain Old Data (POD) type (C++ 3.9p10).
Definition: Type.cpp:2361
clang::ASTContext::GE_None
@ GE_None
No error.
Definition: ASTContext.h:2195
clang::VarDecl::getTemplateSpecializationKind
TemplateSpecializationKind getTemplateSpecializationKind() const
If this variable is an instantiation of a variable template or a static data member of a class templa...
Definition: Decl.cpp:2647
clang::Sema::mergeSwiftNameAttr
SwiftNameAttr * mergeSwiftNameAttr(Decl *D, const SwiftNameAttr &SNA, StringRef Name)
clang::FunctionDefinitionKind::Definition
@ Definition
SDK_Using
@ SDK_Using
Definition: SemaDecl.cpp:7773
clang::SC_PrivateExtern
@ SC_PrivateExtern
Definition: Specifiers.h:238
clang::Qualifiers::addConst
void addConst()
Definition: Type.h:267
clang::DeclContextLookupResult::end
iterator end()
Definition: DeclBase.h:1315
clang::EnumDecl::Create
static EnumDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, EnumDecl *PrevDecl, bool IsScoped, bool IsScopedUsingClassTag, bool IsFixed)
Definition: Decl.cpp:4440
clang::QualType::DestructionKind
DestructionKind
Definition: Type.h:1204
clang::ASTContext::CharTy
CanQualType CharTy
Definition: ASTContext.h:1094
InvalidKernelParam
@ InvalidKernelParam
Definition: SemaDecl.cpp:8889
clang::TSK_ExplicitSpecialization
@ TSK_ExplicitSpecialization
This template specialization was declared or defined by an explicit specialization (C++ [temp....
Definition: Specifiers.h:183
clang::sema::FunctionScopeInfo::ObjCWarnForNoDesignatedInitChain
bool ObjCWarnForNoDesignatedInitChain
This starts true for a method marked as designated initializer and will be set to false if there is a...
Definition: ScopeInfo.h:151
clang::DeclSpec::TST_decltype
static const TST TST_decltype
Definition: DeclSpec.h:291
clang::Decl::attrs
attr_range attrs() const
Definition: DeclBase.h:500
clang::Declarator::isInvalidType
bool isInvalidType() const
Definition: DeclSpec.h:2557
clang::FunctionProtoType::getNumParams
unsigned getNumParams() const
Definition: Type.h:4110
AttrCompatibleWithMultiVersion
static bool AttrCompatibleWithMultiVersion(attr::Kind Kind, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:10425
clang::Type::isPipeType
bool isPipeType() const
Definition: Type.h:6988
clang::ASTContext::attachCommentsToJustParsedDecls
void attachCommentsToJustParsedDecls(ArrayRef< Decl * > Decls, const Preprocessor *PP)
Searches existing comments for doc comments that should be attached to Decls.
Definition: ASTContext.cpp:481
clang::DeclaratorDecl::setQualifierInfo
void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc)
Definition: Decl.cpp:1900
clang::ASTContext::getTypeAlign
unsigned getTypeAlign(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in bits.
Definition: ASTContext.h:2313
ASTConsumer.h
createFriendTagNNSFixIt
static FixItHint createFriendTagNNSFixIt(Sema &SemaRef, NamedDecl *ND, Scope *S, SourceLocation NameLoc)
Add a minimal nested name specifier fixit hint to allow lookup of a tag name from an outer enclosing ...
Definition: SemaDecl.cpp:15772
clang::Type::isReserveIDT
bool isReserveIDT() const
Definition: Type.h:6967
clang::ParsedAttributes
ParsedAttributes - A collection of parsed attributes.
Definition: ParsedAttr.h:1006
clang::Module::isModulePurview
bool isModulePurview() const
Does this Module scope describe part of the purview of a named C++ module?
Definition: Module.h:161
clang::RecordDecl::hasObjectMember
bool hasObjectMember() const
Definition: Decl.h:3966
clang::DeclContext::Encloses
bool Encloses(const DeclContext *DC) const
Determine whether this declaration context encloses the declaration context DC.
Definition: DeclBase.cpp:1221
clang::ASTContext::getObjCSelType
QualType getObjCSelType() const
Retrieve the type that corresponds to the predefined Objective-C 'SEL' type.
Definition: ASTContext.h:2040
clang::LookupResult::getResultKind
LookupResultKind getResultKind() const
Definition: Lookup.h:321
clang::Sema::PushOnScopeChains
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1498
clang::DeclSpec::getConstexprSpecifier
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:754
clang::Sema::CFT_Device
@ CFT_Device
Definition: Sema.h:12801
clang::Redeclarable::getMostRecentDecl
decl_type * getMostRecentDecl()
Returns the most recent (re)declaration of this declaration.
Definition: Redeclarable.h:226
clang::DeclContext::isFileContext
bool isFileContext() const
Definition: DeclBase.h:1942
clang::ObjCMethodDecl::isOptional
bool isOptional() const
Definition: DeclObjC.h:509
clang::Sema::ContextRAII
A RAII object to temporarily push a declaration context.
Definition: Sema.h:1156
clang::NestedNameSpecifierLoc::getPrefix
NestedNameSpecifierLoc getPrefix() const
Return the prefix of this nested-name-specifier.
Definition: NestedNameSpecifier.h:327
clang::sema::LambdaScopeInfo::IntroducerRange
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:835
clang::Sema::ActOnFileScopeAsmDecl
Decl * ActOnFileScopeAsmDecl(Expr *expr, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: SemaDecl.cpp:18745
clang::DeclaratorChunk::getAttrs
const ParsedAttributesView & getAttrs() const
If there are attributes applied to this declaratorchunk, return them.
Definition: DeclSpec.h:1573
clang::AttributeCommonInfo::AS_Declspec
@ AS_Declspec
__declspec(...)
Definition: AttributeCommonInfo.h:36
clang::Sema::LookupSingleName
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
Definition: SemaLookup.cpp:3094
clang::sema::FunctionScopeInfo::isCoroutine
bool isCoroutine() const
Definition: ScopeInfo.h:479
clang::TemplateParameterList::size
unsigned size() const
Definition: DeclTemplate.h:129
clang::Sema::CurrentInstantiationScope
LocalInstantiationScope * CurrentInstantiationScope
The current instantiation scope used to store local variables.
Definition: Sema.h:9581
PreviousDeclsHaveMultiVersionAttribute
static bool PreviousDeclsHaveMultiVersionAttribute(const FunctionDecl *FD)
Definition: SemaDecl.cpp:10661
clang::VarDecl::getInit
const Expr * getInit() const
Definition: Decl.h:1284
clang::FunctionType::ExtInfo
A class which abstracts out some details necessary for making a call.
Definition: Type.h:3672
clang::Sema::DiagnoseUnknownTypeName
void DiagnoseUnknownTypeName(IdentifierInfo *&II, SourceLocation IILoc, Scope *S, CXXScopeSpec *SS, ParsedType &SuggestedType, bool IsTemplateName=false)
Definition: SemaDecl.cpp:680
getNextLargerIntegralType
static QualType getNextLargerIntegralType(ASTContext &Context, QualType T)
Definition: SemaDecl.cpp:18035
clang::CXXRecordDecl::hasTrivialDestructor
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1321
clang::Sema::CreateBuiltin
FunctionDecl * CreateBuiltin(IdentifierInfo *II, QualType Type, unsigned ID, SourceLocation Loc)
Definition: SemaDecl.cpp:2195
clang::RecordDecl::setNonTrivialToPrimitiveDestroy
void setNonTrivialToPrimitiveDestroy(bool V)
Definition: Decl.h:4004
clang::Expr::isValueDependent
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:168
clang::Type::isStandardLayoutType
bool isStandardLayoutType() const
Test if this type is a standard-layout type.
Definition: Type.cpp:2647
clang::IdentifierInfo
One of these records is kept for each identifier that is lexed.
Definition: IdentifierTable.h:84
clang::Sema::areMultiversionVariantFunctionsCompatible
bool areMultiversionVariantFunctionsCompatible(const FunctionDecl *OldFD, const FunctionDecl *NewFD, const PartialDiagnostic &NoProtoDiagID, const PartialDiagnosticAt &NoteCausedDiagIDAt, const PartialDiagnosticAt &NoSupportDiagIDAt, const PartialDiagnosticAt &DiffDiagIDAt, bool TemplatesSupported, bool ConstexprSupported, bool CLinkageMayDiffer)
Checks if the variant/multiversion functions are compatible.
Definition: SemaDecl.cpp:10477
clang::Sema::getTemplateNameKindForDiagnostics
TemplateNameKindForDiagnostics getTemplateNameKindForDiagnostics(TemplateName Name)
Definition: SemaDecl.cpp:1286
clang::transformer::member
RangeSelector member(std::string ID)
Given a MemberExpr, selects the member token.
Definition: RangeSelector.cpp:188
clang::FunctionDecl::isThisDeclarationInstantiatedFromAFriendDefinition
bool isThisDeclarationInstantiatedFromAFriendDefinition() const
Determine whether this specific declaration of the function is a friend declaration that was instanti...
Definition: Decl.cpp:2996
clang::TypedefDecl
Represents the declaration of a typedef-name via the 'typedef' type specifier.
Definition: Decl.h:3286
clang::FunctionDecl::setVirtualAsWritten
void setVirtualAsWritten(bool V)
State that this function is marked as virtual explicitly.
Definition: Decl.h:2186
clang::ASTContext::getTargetInfo
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:764
clang::Expr::EvaluateAsInt
bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx, SideEffectsKind AllowSideEffects=SE_NoSideEffects, bool InConstantContext=false) const
EvaluateAsInt - Return true if this is a constant which we can fold and convert to an integer,...
Definition: ExprConstant.cpp:14929
clang::RecordDecl::field_end
field_iterator field_end() const
Definition: Decl.h:4108
clang::OpaquePtr< QualType >::make
static OpaquePtr make(QualType P)
Definition: Ownership.h:60
clang::Sema::CheckMain
void CheckMain(FunctionDecl *FD, const DeclSpec &D)
Definition: SemaDecl.cpp:11352
clang::TypoCorrection::getCorrectionAsIdentifierInfo
IdentifierInfo * getCorrectionAsIdentifierInfo() const
Definition: TypoCorrection.h:86
clang::Sema::mergeUuidAttr
UuidAttr * mergeUuidAttr(Decl *D, const AttributeCommonInfo &CI, StringRef UuidAsWritten, MSGuidDecl *GuidDecl)
clang::Sema::MergeSYCLAddIRAttributesFunctionAttr
SYCLAddIRAttributesFunctionAttr * MergeSYCLAddIRAttributesFunctionAttr(Decl *D, const SYCLAddIRAttributesFunctionAttr &A)
clang::PartialDiagnostic::getDiagID
unsigned getDiagID() const
Definition: PartialDiagnostic.h:141
clang::DeclaratorChunk::MemberPointerTypeInfo::Scope
CXXScopeSpec & Scope()
Definition: DeclSpec.h:1530
clang::VarDecl::isPreviousDeclInSameBlockScope
bool isPreviousDeclInSameBlockScope() const
Whether this local extern variable declaration's previous declaration was declared in the same block ...
Definition: Decl.h:1501
clang::Sema::BuildDeclaratorGroup
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:13836
clang::PartialDiagnostic
Definition: PartialDiagnostic.h:31
clang::LangOptions
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:58
clang::FunctionDecl::isExternC
bool isExternC() const
Determines whether this function is a function with external, C linkage.
Definition: Decl.cpp:3239
clang::Type::isBooleanType
bool isBooleanType() const
Definition: Type.h:7173
clang::MemberPointerType
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:2846
clang::VarDecl::getTSCSpec
ThreadStorageClassSpecifier getTSCSpec() const
Definition: Decl.h:1093
clang::Decl::setObjectOfFriendDecl
void setObjectOfFriendDecl(bool PerformFriendInjection=false)
Changes the namespace of this declaration to reflect that it's the object of a friend declaration.
Definition: DeclBase.h:1111
clang::ParenTypeLoc::setRParenLoc
void setRParenLoc(SourceLocation Loc)
Definition: TypeLoc.h:1161
clang::ObjCPropertyAttribute::Kind
Kind
Definition: DeclObjCCommon.h:22
isDefaultStdCall
static bool isDefaultStdCall(FunctionDecl *FD, Sema &S)
Definition: SemaDecl.cpp:11507
clang::Sema::SemaDiagnosticBuilder
A generic diagnostic builder for errors which may or may not be deferred.
Definition: Sema.h:1940
clang::BinaryConditionalOperator::getFalseExpr
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression which will be evaluated if the condnition evaluates to false;...
Definition: Expr.h:4315
clang::DeclContext::getInnermostBlockDecl
const BlockDecl * getInnermostBlockDecl() const
Return this DeclContext if it is a BlockDecl.
Definition: DeclBase.cpp:1118
clang::Sema::CheckFunctionDeclaration
bool CheckFunctionDeclaration(Scope *S, FunctionDecl *NewFD, LookupResult &Previous, bool IsMemberSpecialization)
Perform semantic checking of a new function declaration.
Definition: SemaDecl.cpp:11023
clang::TemplateParameterList::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Definition: DeclTemplate.h:197
clang::InitializationKind
Describes the kind of initialization being performed, along with location information for tokens rela...
Definition: Initialization.h:566
clang::Sema::getObjCInterfaceDecl
ObjCInterfaceDecl * getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection=false)
Look for an Objective-C class in the translation unit.
Definition: SemaDecl.cpp:2121
clang::ActionResult
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc.
Definition: Ownership.h:152
SDK_Local
@ SDK_Local
Definition: SemaDecl.cpp:7768
clang::Type::isObjCObjectType
bool isObjCObjectType() const
Definition: Type.h:6882
clang::ArrayTypeLoc
Wrapper for source info for arrays.
Definition: TypeLoc.h:1516
shouldWarnIfShadowedDecl
static bool shouldWarnIfShadowedDecl(const DiagnosticsEngine &Diags, const LookupResult &R)
Definition: SemaDecl.cpp:7803
clang::DeclSpec::getRepAsDecl
Decl * getRepAsDecl() const
Definition: DeclSpec.h:490
clang::FunctionTemplateDecl::getTemplatedDecl
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
Definition: DeclTemplate.h:1034
checkAttributesAfterMerging
static void checkAttributesAfterMerging(Sema &S, NamedDecl &ND)
Definition: SemaDecl.cpp:6625
clang::MangleNumberingContext
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
Definition: MangleNumberingContext.h:29
clang::ConstantArrayType::getNumAddressingBits
static unsigned getNumAddressingBits(const ASTContext &Context, QualType ElementType, const llvm::APInt &NumElements)
Determine the number of bits required to address a member of.
Definition: Type.cpp:141
clang::ElaboratedTypeLoc
Definition: TypeLoc.h:2260
clang::DeclFilterCCC
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
Definition: TypoCorrection.h:366
clang::Sema::getEmissionStatus
FunctionEmissionStatus getEmissionStatus(FunctionDecl *Decl, bool Final=false)
Definition: SemaDecl.cpp:18835
CheckMultiVersionFirstFunction
static bool CheckMultiVersionFirstFunction(Sema &S, FunctionDecl *FD, MultiVersionKind MVKind, const TargetAttr *TA)
Check the validity of a multiversion function declaration that is the first of its kind.
Definition: SemaDecl.cpp:10636
clang::Sema::DeviceDiagnosticReason::OmpDevice
@ OmpDevice
OpenMP specific diagnostic.
clang::TypeLoc::IgnoreParens
TypeLoc IgnoreParens() const
Definition: TypeLoc.h:1183
clang::NamespaceDecl::isAnonymousNamespace
bool isAnonymousNamespace() const
Returns true if this is an anonymous namespace declaration.
Definition: Decl.h:597
DiagnoseInvalidRedeclaration
static NamedDecl * DiagnoseInvalidRedeclaration(Sema &SemaRef, LookupResult &Previous, FunctionDecl *NewFD, ActOnFDArgs &ExtraArgs, bool IsLocalFriend, Scope *S)
Generate diagnostics for an invalid function redeclaration.
Definition: SemaDecl.cpp:8535
clang::ASTContext::setjmp_bufDecl
void setjmp_bufDecl(TypeDecl *jmp_bufDecl)
Set the type for the C jmp_buf type.
Definition: ASTContext.h:1930
clang::sema::LambdaScopeInfo
Definition: ScopeInfo.h:825
clang::ObjCMethodDecl
ObjCMethodDecl - Represents an instance or class method declaration.
Definition: DeclObjC.h:139
clang::TargetInfo::getShortWidth
unsigned getShortWidth() const
Return the size of 'signed short' and 'unsigned short' for this target, in bits.
Definition: TargetInfo.h:446
clang::Type::isEventT
bool isEventT() const
Definition: Type.h:6955
clang::PointerType
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2655
clang::RecordDecl::setNonTrivialToPrimitiveDefaultInitialize
void setNonTrivialToPrimitiveDefaultInitialize(bool V)
Definition: Decl.h:3988
clang::TST_class
@ TST_class
Definition: Specifiers.h:79
ScopeInfo.h
clang::Sema::CheckStaticLocalForDllExport
void CheckStaticLocalForDllExport(VarDecl *VD)
Check if VD needs to be dllexport/dllimport due to being in a dllexport/import function.
Definition: SemaDecl.cpp:13554
clang::Type::isSampledImageType
bool isSampledImageType() const
Definition: Type.h:6978
clang::Builtin::Context::isTSBuiltin
bool isTSBuiltin(unsigned ID) const
Return true if this function is a target-specific builtin.
Definition: Builtins.h:96
clang::ast_matchers::recordType
const AstTypeMatcher< RecordType > recordType
Matches record types (e.g.
Definition: ASTMatchersInternal.cpp:1059
clang::DeclSpec::TST_unspecified
static const TST TST_unspecified
Definition: DeclSpec.h:260
clang::LangAS::Default
@ Default
clang::FunctionDecl::isMSVCRTEntryPoint
bool isMSVCRTEntryPoint() const
Determines whether this function is a MSVCRT user defined entry point.
Definition: Decl.cpp:3092
isRecordType
static bool isRecordType(QualType T)
Definition: SemaExprMember.cpp:1216
clang::FunctionTypeLoc::getLParenLoc
SourceLocation getLParenLoc() const
Definition: TypeLoc.h:1418
clang::DecompositionDeclarator
A parsed C++17 decomposition declarator of the form '[' identifier-list ']'.
Definition: DeclSpec.h:1702
clang::DeclaratorDecl::setTypeSourceInfo
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:762
clang::Type::getBaseElementTypeUnsafe
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:7213
clang::Qualifiers::OCL_None
@ OCL_None
There is no lifetime qualification on this type.
Definition: Type.h:164
clang::VarDecl::isExternC
bool isExternC() const
Determines whether this variable is a variable with external, C linkage.
Definition: Decl.cpp:2146
clang::Type::isHalfType
bool isHalfType() const
Definition: Type.h:7061
clang::BinaryOperator::isCompoundAssignmentOp
static bool isCompoundAssignmentOp(Opcode Opc)
Definition: Expr.h:4001
clang::PointerLikeTypeLoc::getPointeeLoc
TypeLoc getPointeeLoc() const
Definition: TypeLoc.h:1240
clang::Sema::CheckEnumRedeclaration
bool CheckEnumRedeclaration(SourceLocation EnumLoc, bool IsScoped, QualType EnumUnderlyingTy, bool IsFixed, const EnumDecl *Prev)
Check whether this is a valid redeclaration of a previous enumeration.
Definition: SemaDecl.cpp:15559
clang::FunctionDecl::isMain
bool isMain() const
Determines whether this function is "main", which is the entry point into an executable program.
Definition: Decl.cpp:3084
clang::ObjCMethodDecl::param_begin
param_const_iterator param_begin() const
Definition: DeclObjC.h:357
clang::sema::CapturingScopeInfo::ImpCap_LambdaByref
@ ImpCap_LambdaByref
Definition: ScopeInfo.h:666
clang::Module::Kind
ModuleKind Kind
The kind of this module.
Definition: Module.h:129
clang::TargetInfo::isValidFeatureName
virtual bool isValidFeatureName(StringRef Feature) const
Determine whether this TargetInfo supports the given feature.
Definition: TargetInfo.h:1297
clang::FileScopeAsmDecl
Definition: Decl.h:4144
clang::FunctionDecl::isLateTemplateParsed
bool isLateTemplateParsed() const
Whether this templated function will be late parsed.
Definition: Decl.h:2194
clang::Sema::BuildMicrosoftCAnonymousStruct
Decl * BuildMicrosoftCAnonymousStruct(Scope *S, DeclSpec &DS, RecordDecl *Record)
BuildMicrosoftCAnonymousStruct - Handle the declaration of an Microsoft C anonymous structure.
Definition: SemaDecl.cpp:5491
clang::DeclaratorContext::TypeName
@ TypeName
clang::Sema::FunctionEmissionStatus::Emitted
@ Emitted
clang::Type::castAsArrayTypeUnsafe
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition: Type.h:7339
clang::VarDecl::TLS_Dynamic
@ TLS_Dynamic
TLS with a dynamic initializer.
Definition: Decl.h:898
clang::ASTContext::getParenType
QualType getParenType(QualType NamedType) const
Definition: ASTContext.cpp:4987
isResultTypeOrTemplate
static bool isResultTypeOrTemplate(LookupResult &R, const Token &NextToken)
Determine whether the given result set contains either a type name or.
Definition: SemaDecl.cpp:795
clang::Sema::mergeImportNameAttr
WebAssemblyImportNameAttr * mergeImportNameAttr(Decl *D, const WebAssemblyImportNameAttr &AL)
clang::CXXConstructorDecl::isCopyConstructor
bool isCopyConstructor(unsigned &TypeQuals) const
Whether this constructor is a copy constructor (C++ [class.copy]p2, which can be used to copy the cla...
Definition: DeclCXX.cpp:2643
clang::FunctionType::ExtInfo::getRegParm
unsigned getRegParm() const
Definition: Type.h:3727
clang::ASTContext::getAddrSpaceQualType
QualType getAddrSpaceQualType(QualType T, LangAS AddressSpace) const
Return the uniqued reference to the type for an address space qualified type with the specified type ...
Definition: ASTContext.cpp:3023
clang::FunctionTemplateDecl::getPreviousDecl
FunctionTemplateDecl * getPreviousDecl()
Retrieve the previous declaration of this function template, or nullptr if no such declaration exists...
Definition: DeclTemplate.h:1060
clang::ParsedTargetAttr::Features
std::vector< std::string > Features
Definition: Attr.h:355
clang::CXXMethodDecl::addOverriddenMethod
void addOverriddenMethod(const CXXMethodDecl *MD)
Definition: DeclCXX.cpp:2402
clang::Sema::isDeclInScope
bool isDeclInScope(NamedDecl *D, DeclContext *Ctx, Scope *S=nullptr, bool AllowInlineNamespace=false)
isDeclInScope - If 'Ctx' is a function/method, isDeclInScope returns true if 'D' is in Scope 'S',...
Definition: SemaDecl.cpp:1556
clang::IdentifierInfo::getName
StringRef getName() const
Return the actual identifier string.
Definition: IdentifierTable.h:195
clang::Builtin::ID
ID
Definition: Builtins.h:49
clang::Sema::CheckParameter
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:14113
clang::LinkageSpecDecl::Create
static LinkageSpecDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExternLoc, SourceLocation LangLoc, LanguageIDs Lang, bool HasBraces)
Definition: DeclCXX.cpp:2801
clang::FunctionProtoType::ExtProtoInfo
Extra information about a function prototype.
Definition: Type.h:3983
clang::CXXBasePath
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
Definition: CXXInheritance.h:70
clang::SourceLocation::isInvalid
bool isInvalid() const
Definition: SourceLocation.h:111
clang::CXXMethodDecl::isConst
bool isConst() const
Definition: DeclCXX.h:2009
clang::Sema::CheckCompleteVariableDeclaration
void CheckCompleteVariableDeclaration(VarDecl *VD)
Definition: SemaDecl.cpp:13253
clang::UnaryOperator::getSubExpr
Expr * getSubExpr() const
Definition: Expr.h:2262
clang::ObjCIvarDecl::Create
static ObjCIvarDecl * Create(ASTContext &C, ObjCContainerDecl *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, AccessControl ac, Expr *BW=nullptr, bool synthesized=false)
Definition: DeclObjC.cpp:1799
clang::FieldDecl::getParent
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3031
clang::Expr::IgnoreParens
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:2944
clang::Sema::LookupNestedNameSpecifierName
@ LookupNestedNameSpecifierName
Look up of a name that precedes the '::' scope resolution operator in C++.
Definition: Sema.h:4324
PartialDiagnostic.h
clang::TSCS__Thread_local
@ TSCS__Thread_local
C11 _Thread_local.
Definition: Specifiers.h:229
clang::Sema::mergeDeclAttributes
void mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3029
clang
Definition: CalledOnceCheck.h:17
clang::Type::isAnyPointerType
bool isAnyPointerType() const
Definition: Type.h:6754
clang::Sema::CFT_Global
@ CFT_Global
Definition: Sema.h:12802
clang::LangOptions::MSVC2015
@ MSVC2015
Definition: LangOptions.h:125
clang::TemplateArgumentListInfo::setRAngleLoc
void setRAngleLoc(SourceLocation Loc)
Definition: TemplateBase.h:583
clang::IndirectFieldDecl
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3093
clang::Sema::mergeObjCMethodDecls
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
Definition: SemaDecl.cpp:4077
clang::DeclContext::lookup
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1657
clang::Sema::ImplicitlyRetainedSelfLocs
llvm::SmallVector< std::pair< SourceLocation, const BlockDecl * >, 1 > ImplicitlyRetainedSelfLocs
List of SourceLocations where 'self' is implicitly retained inside a block.
Definition: Sema.h:1666
clang::DeclarationNameInfo::setLoc
void setLoc(SourceLocation L)
setLoc - Sets the main location of the declaration name.
Definition: DeclarationName.h:788
clang::FunctionDecl::setHasSkippedBody
void setHasSkippedBody(bool Skipped=true)
Definition: Decl.h:2426
clang::Sema::DeviceDiagnosticReason::OmpHost
@ OmpHost
clang::Decl::OBJC_TQ_CSNullability
@ OBJC_TQ_CSNullability
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition: DeclBase.h:207
clang::VarDecl::DeclarationOnly
@ DeclarationOnly
This declaration is only a declaration.
Definition: Decl.h:1211
clang::QualType::withoutLocalFastQualifiers
QualType withoutLocalFastQualifiers() const
Definition: Type.h:903
clang::Type::isArrayType
bool isArrayType() const
Definition: Type.h:6816
clang::Sema::checkVarDeclRedefinition
bool checkVarDeclRedefinition(VarDecl *OldDefn, VarDecl *NewDefn)
We've just determined that Old and New both appear to be definitions of the same variable.
Definition: SemaDecl.cpp:4541
clang::ASTContext::toCharUnitsFromBits
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
Definition: ASTContext.cpp:2461
clang::UnqualifiedIdKind::IK_ConversionFunctionId
@ IK_ConversionFunctionId
A conversion function name, e.g., operator int.
clang::TargetInfo::allowDebugInfoForExternalRef
virtual bool allowDebugInfoForExternalRef() const
Whether target allows debuginfo types for decl only variables/functions.
Definition: TargetInfo.h:1622
clang::FunctionDecl::setDescribedFunctionTemplate
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:3737
clang::Sema::ActOnEnumBody
void ActOnEnumBody(SourceLocation EnumLoc, SourceRange BraceRange, Decl *EnumDecl, ArrayRef< Decl * > Elements, Scope *S, const ParsedAttributesView &Attr)
Definition: SemaDecl.cpp:18518
clang::NestedNameSpecifier::getAsType
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
Definition: NestedNameSpecifier.h:196
clang::Builtin::Context
Holds information about both target-independent and target-specific builtins, allowing easy queries b...
Definition: Builtins.h:68
clang::Sema::ActOnTagStartSkippedDefinition
SkippedDefinitionContext ActOnTagStartSkippedDefinition(Scope *S, Decl *TD)
Invoked when we enter a tag definition that we're skipping.
Definition: SemaDecl.cpp:1319
clang::CXXBaseSpecifier::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclCXX.h:191
clang::DeclSpec::TST_atomic
static const TST TST_atomic
Definition: DeclSpec.h:297
clang::Sema::ActOnDocumentableDecl
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:13876
clang::FunctionTemplateDecl::getInstantiatedFromMemberTemplate
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
Definition: DeclTemplate.h:1078
clang::Qualifiers::getObjCLifetime
ObjCLifetime getObjCLifetime() const
Definition: Type.h:337
clang::Sema::ActOnDuplicateDefinition
bool ActOnDuplicateDefinition(DeclSpec &DS, Decl *Prev, SkipBodyInfo &SkipBody)
Perform ODR-like check for C/ObjC when merging tag types from modules.
Definition: SemaDecl.cpp:16783
clang::Sema::MergeIntelReqdSubGroupSizeAttr
IntelReqdSubGroupSizeAttr * MergeIntelReqdSubGroupSizeAttr(Decl *D, const IntelReqdSubGroupSizeAttr &A)
clang::GVA_AvailableExternally
@ GVA_AvailableExternally
Definition: Linkage.h:75
clang::DeclaratorContext::Block
@ Block
isAttributeTargetADefinition
static bool isAttributeTargetADefinition(Decl *D)
Definition: SemaDecl.cpp:2570
clang::Sema::CheckConstructorDeclarator
QualType CheckConstructorDeclarator(Declarator &D, QualType R, StorageClass &SC)
CheckConstructorDeclarator - Called by ActOnDeclarator to check the well-formedness of the constructo...
Definition: SemaDeclCXX.cpp:10453
checkNonMultiVersionCompatAttributes
static bool checkNonMultiVersionCompatAttributes(Sema &S, const FunctionDecl *FD, const FunctionDecl *CausedFD, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:10440
clang::Stmt
Stmt - This represents one statement.
Definition: Stmt.h:69
clang::EST_BasicNoexcept
@ EST_BasicNoexcept
noexcept
Definition: ExceptionSpecificationType.h:26
clang::ObjCIvarDecl
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1923
clang::QualType::isNonTrivialToPrimitiveCopy
PrimitiveCopyKind isNonTrivialToPrimitiveCopy() const
Check if this is a non-trivial type that would cause a C struct transitively containing this type to ...
Definition: Type.cpp:2544
clang::Sema::RegisterLocallyScopedExternCDecl
void RegisterLocallyScopedExternCDecl(NamedDecl *ND, Scope *S)
Register the given locally-scoped extern "C" declaration so that it can be found later for redeclarat...
Definition: SemaDecl.cpp:6316
clang::Scope::getEntity
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition: Scope.h:343
clang::Sema::mergeInternalLinkageAttr
InternalLinkageAttr * mergeInternalLinkageAttr(Decl *D, const ParsedAttr &AL)
clang::VarDecl::isConstexpr
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition: Decl.h:1478
clang::UnaryOperator::getOpcode
Opcode getOpcode() const
Definition: Expr.h:2257
clang::BinaryOperator::getRHS
Expr * getRHS() const
Definition: Expr.h:3912
clang::Sema::AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction
void AddKnownFunctionAttributesForReplaceableGlobalAllocationFunction(FunctionDecl *FD)
If this function is a C++ replaceable global allocation function (C++2a [basic.stc....
Definition: SemaDecl.cpp:15240
clang::ASTContext::SignedCharTy
CanQualType SignedCharTy
Definition: ASTContext.h:1101
clang::TemplateIdAnnotation::getTemplateArgs
ParsedTemplateArgument * getTemplateArgs()
Retrieves a pointer to the template arguments.
Definition: ParsedTemplate.h:192
clang::Sema::isIncompatibleTypedef
bool isIncompatibleTypedef(TypeDecl *Old, TypedefNameDecl *New)
Definition: SemaDecl.cpp:2339
clang::Declarator::isCtorOrDtor
bool isCtorOrDtor()
Returns true if this declares a constructor or a destructor.
Definition: DeclSpec.cpp:420
clang::Builtin::Context::allowTypeMismatch
bool allowTypeMismatch(unsigned ID) const
Determines whether a declaration of this builtin should be recognized even if the type doesn't match ...
Definition: Builtins.h:166
clang::CXXRecordDecl::getCanonicalDecl
CXXRecordDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: DeclCXX.h:501
clang::Declarator
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1803
clang::Sema::CheckEnumUnderlyingType
bool CheckEnumUnderlyingType(TypeSourceInfo *TI)
Check that this is a valid underlying type for an enum declaration.
Definition: SemaDecl.cpp:15538
clang::SourceManager::isInSystemHeader
bool isInSystemHeader(SourceLocation Loc) const
Returns if a SourceLocation is in a system header.
Definition: SourceManager.h:1488
clang::sema::LambdaScopeInfo::ShadowingDecls
llvm::SmallVector< ShadowedOuterDecl, 4 > ShadowingDecls
Definition: ScopeInfo.h:904
clang::Type::isDependentAddressSpaceType
bool isDependentAddressSpaceType() const
Definition: Type.h:6874
clang::NestedNameSpecifierLoc::getNestedNameSpecifier
NestedNameSpecifier * getNestedNameSpecifier() const
Retrieve the nested-name-specifier to which this instance refers.
Definition: NestedNameSpecifier.h:274
clang::EnumDecl::getIntegerType
QualType getIntegerType() const
Return the integer type this enum decl corresponds to.
Definition: Decl.h:3772
clang::CXXRecordDecl::bases_begin
base_class_iterator bases_begin()
Definition: DeclCXX.h:603
clang::LookupResult::Filter
A class for iterating through a result set and possibly filtering out results.
Definition: Lookup.h:617
clang::Sema::getImplicitCodeSegOrSectionAttrForFunction
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
Definition: SemaDecl.cpp:10306
clang::TypoCorrection::getCorrectionDecl
NamedDecl * getCorrectionDecl() const
Gets the pointer to the declaration of the typo correction.
Definition: TypoCorrection.h:151
clang::Sema::ActOnPragmaWeakAlias
void ActOnPragmaWeakAlias(IdentifierInfo *WeakName, IdentifierInfo *AliasName, SourceLocation PragmaLoc, SourceLocation WeakNameLoc, SourceLocation AliasNameLoc)
ActOnPragmaWeakAlias - Called on well formed #pragma weak ident = ident.
Definition: SemaDecl.cpp:18796
clang::ElaboratedTypeLoc::setQualifierLoc
void setQualifierLoc(NestedNameSpecifierLoc QualifierLoc)
Definition: TypeLoc.h:2278
clang::Module::ModulePartitionImplementation
@ ModulePartitionImplementation
This is a C++ 20 module partition implementation.
Definition: Module.h:119
clang::QualType::isNonTrivialToPrimitiveDefaultInitialize
PrimitiveDefaultInitializeKind isNonTrivialToPrimitiveDefaultInitialize() const
Functions to query basic properties of non-trivial C struct types.
Definition: Type.cpp:2528
clang::Expr::getType
QualType getType() const
Definition: Expr.h:141
PtrKernelParam
@ PtrKernelParam
Definition: SemaDecl.cpp:8887
clang::CXXScopeSpec::getScopeRep
NestedNameSpecifier * getScopeRep() const
Retrieve the representation of the nested-name-specifier.
Definition: DeclSpec.h:77
clang::SourceLocation::isValid
bool isValid() const
Return true if this is a valid SourceLocation object.
Definition: SourceLocation.h:110
clang::Builtin::Context::isPure
bool isPure(unsigned ID) const
Return true if this function has no side effects.
Definition: Builtins.h:101
clang::DeclAttrsMatchCUDAMode
bool DeclAttrsMatchCUDAMode(const LangOptions &LangOpts, Decl *D)
Definition: SemaInternal.h:44
clang::CXXBaseSpecifier
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
clang::CorrectionCandidateCallback
Base class for callback objects used by Sema::CorrectTypo to check the validity of a potential typo c...
Definition: TypoCorrection.h:281
clang::Sema::getCallingConvAttributedType
const AttributedType * getCallingConvAttributedType(QualType T) const
Get the outermost AttributedType node that sets a calling convention.
Definition: SemaDecl.cpp:3289
clang::Attr
Attr - This represents one attribute.
Definition: Attr.h:44
clang::CXXRecordDecl::hasDefinition
bool hasDefinition() const
Definition: DeclCXX.h:549
clang::LookupResult::Found
@ Found
Name lookup found a single declaration that met the criteria.
Definition: Lookup.h:59
clang::TypeSourceInfo
A container of type source information.
Definition: Type.h:6473
PtrPtrKernelParam
@ PtrPtrKernelParam
Definition: SemaDecl.cpp:8886
clang::FunctionType::getReturnType
QualType getReturnType() const
Definition: Type.h:3824
clang::Sema::mergeAvailabilityAttr
AvailabilityAttr * mergeAvailabilityAttr(NamedDecl *D, const AttributeCommonInfo &CI, IdentifierInfo *Platform, bool Implicit, VersionTuple Introduced, VersionTuple Deprecated, VersionTuple Obsoleted, bool IsUnavailable, StringRef Message, bool IsStrict, StringRef Replacement, AvailabilityMergeKind AMK, int Priority)
Attribute merging methods. Return true if a new attribute was added.
clang::SourceManager::getFileEntryForID
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
Definition: SourceManager.h:1030
clang::NamedDecl::getDeclName
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:311
clang::hasAttribute
int hasAttribute(AttrSyntax Syntax, const IdentifierInfo *Scope, const IdentifierInfo *Attr, const TargetInfo &Target, const LangOptions &LangOpts)
Return the version number associated with the attribute if we recognize and implement the attribute s...
Definition: Attributes.cpp:8
clang::DefaultInitializedTypeVisitor
Definition: NonTrivialTypeVisitor.h:50
clang::FixItHint::CreateRemoval
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
clang::DeclSpec::getTypeQualifiers
unsigned getTypeQualifiers() const
getTypeQualifiers - Return a set of TQs.
Definition: DeclSpec.h:547
clang::Declarator::getTypeObject
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2240
InvalidAddrSpacePtrKernelParam
@ InvalidAddrSpacePtrKernelParam
Definition: SemaDecl.cpp:8888
getFunctionStorageClass
static StorageClass getFunctionStorageClass(Sema &SemaRef, Declarator &D)
Definition: SemaDecl.cpp:8686
clang::Sema::MergeSYCLIntelPipeIOAttr
SYCLIntelPipeIOAttr * MergeSYCLIntelPipeIOAttr(Decl *D, const SYCLIntelPipeIOAttr &A)
clang::TargetInfo::supportsMultiVersioning
bool supportsMultiVersioning() const
Identify whether this target supports multiversioning of functions, which requires support for cpu_su...
Definition: TargetInfo.h:1347
clang::DeclContext::isDependentContext
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1151
clang::MultiVersionKind::CPUSpecific
@ CPUSpecific
clang::LookupResult::getLookupKind
Sema::LookupNameKind getLookupKind() const
Gets the kind of lookup to perform.
Definition: Lookup.h:253
clang::Scope::RemoveDecl
void RemoveDecl(Decl *D)
Definition: Scope.h:310
clang::Sema::ActOnTagStartDefinition
void ActOnTagStartDefinition(Scope *S, Decl *TagDecl)
ActOnTagStartDefinition - Invoked when we have entered the scope of a tag's definition (e....
Definition: SemaDecl.cpp:16769
unsigned
clang::ASTContext::getQualifiedTemplateName
TemplateName getQualifiedTemplateName(NestedNameSpecifier *NNS, bool TemplateKeyword, TemplateDecl *Template) const
Retrieve the template name that represents a qualified template name such as std::vector.
Definition: ASTContext.cpp:8994
clang::DeclSpec::isVirtualSpecified
bool isVirtualSpecified() const
Definition: DeclSpec.h:578
clang::Builtin::Context::isHeaderDependentFunction
bool isHeaderDependentFunction(unsigned ID) const
Returns true if this builtin requires appropriate header in other compilers.
Definition: Builtins.h:148
clang::Sema::MergeSYCLIntelMaxWorkGroupSizeAttr
SYCLIntelMaxWorkGroupSizeAttr * MergeSYCLIntelMaxWorkGroupSizeAttr(Decl *D, const SYCLIntelMaxWorkGroupSizeAttr &A)
clang::SC_Auto
@ SC_Auto
Definition: Specifiers.h:241
clang::FunctionProtoType::ExtProtoInfo::TypeQuals
Qualifiers TypeQuals
Definition: Type.h:3987
clang::Stmt::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Stmt.cpp:336
clang::sema::CapturingScopeInfo::addThisCapture
void addThisCapture(bool isNested, SourceLocation Loc, QualType CaptureType, bool ByCopy)
Definition: ScopeInfo.h:1047
adjustDeclContextForDeclaratorDecl
static void adjustDeclContextForDeclaratorDecl(DeclaratorDecl *NewD, DeclaratorDecl *OldD)
If necessary, adjust the semantic declaration context for a qualified declaration to name the correct...
Definition: SemaDecl.cpp:3371
clang::Sema::checkNonTrivialCUnion
void checkNonTrivialCUnion(QualType QT, SourceLocation Loc, NonTrivialCUnionContext UseContext, unsigned NonTrivialKind)
Emit diagnostics if a non-trivial C union type or a struct that contains a non-trivial C union is use...
Definition: SemaDecl.cpp:12347
clang::Sema::adjustContextForLocalExternDecl
static bool adjustContextForLocalExternDecl(DeclContext *&DC)
Adjust the DeclContext for a function or variable that might be a function-local external declaration...
Definition: SemaDecl.cpp:6943
clang::Sema::ActOnFunctionDeclarator
NamedDecl * ActOnFunctionDeclarator(Scope *S, Declarator &D, DeclContext *DC, TypeSourceInfo *TInfo, LookupResult &Previous, MultiTemplateParamsArg TemplateParamLists, bool &AddToScope)
Definition: SemaDecl.cpp:9195
clang::DeclaratorChunk
One instance of this struct is used for each type in a declarator that is parsed.
Definition: DeclSpec.h:1173
clang::RecordDecl::isMsStruct
bool isMsStruct(const ASTContext &C) const
Get whether or not this is an ms_struct which can be turned on with an attribute, pragma,...
Definition: Decl.cpp:4663
clang::FunctionDecl::isExplicitlyDefaulted
bool isExplicitlyDefaulted() const
Whether this function is explicitly defaulted.
Definition: Decl.h:2219
clang::VarDecl::Definition
@ Definition
This declaration is definitely a definition.
Definition: Decl.h:1217
clang::TSCS___thread
@ TSCS___thread
GNU __thread.
Definition: Specifiers.h:223
clang::NestedNameSpecifierLocBuilder::MakeTrivial
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: NestedNameSpecifier.cpp:631
clang::InitializedEntity
Describes an entity that is being initialized.
Definition: Initialization.h:47
clang::FunctionDecl::isVariadic
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:2940
clang::PointerTypeLoc::setStarLoc
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1265
clang::Type::isConstantArrayType
bool isConstantArrayType() const
Definition: Type.h:6820
MultiVersionTypesCompatible
static bool MultiVersionTypesCompatible(MultiVersionKind Old, MultiVersionKind New)
Definition: SemaDecl.cpp:10742
clang::ASTContext::setsigjmp_bufDecl
void setsigjmp_bufDecl(TypeDecl *sigjmp_bufDecl)
Set the type for the C sigjmp_buf type.
Definition: ASTContext.h:1942
clang::AttributeCommonInfo::AS_Pragma
@ AS_Pragma
#pragma ...
Definition: AttributeCommonInfo.h:45
CheckMultiVersionFunction
static bool CheckMultiVersionFunction(Sema &S, FunctionDecl *NewFD, bool &Redeclaration, NamedDecl *&OldDecl, LookupResult &Previous)
Check the validity of a mulitversion function declaration.
Definition: SemaDecl.cpp:10933
clang::TagDecl::getTagKind
TagKind getTagKind() const
Definition: Decl.h:3529
clang::Sema::ExitDeclaratorContext
void ExitDeclaratorContext(Scope *S)
Definition: SemaDecl.cpp:1375
clang::InitializedEntity::InitializeVariable
static InitializedEntity InitializeVariable(VarDecl *Var)
Create the initialization entity for a variable.
Definition: Initialization.h:248
clang::Sema::MergeSYCLAddIRAttributesKernelParameterAttr
SYCLAddIRAttributesKernelParameterAttr * MergeSYCLAddIRAttributesKernelParameterAttr(Decl *D, const SYCLAddIRAttributesKernelParameterAttr &A)
clang::TypedefNameDecl
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3184
clang::FunctionDecl::param_begin
param_iterator param_begin()
Definition: Decl.h:2499
clang::ParenListExpr::getExprs
Expr ** getExprs()
Definition: Expr.h:5627
clang::Decl::getAttrs
AttrVec & getAttrs()
Definition: DeclBase.h:489
CheckForDuplicateEnumValues
static void CheckForDuplicateEnumValues(Sema &S, ArrayRef< Decl * > Elements, EnumDecl *Enum, QualType EnumType)
Definition: SemaDecl.cpp:18379
clang::LookupResult::getFoundDecl
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:517
clang::LookupResult::getAsSingle
DeclClass * getAsSingle() const
Definition: Lookup.h:507
CheckMultiVersionAdditionalRules
static bool CheckMultiVersionAdditionalRules(Sema &S, const FunctionDecl *OldFD, const FunctionDecl *NewFD, bool CausesMV, MultiVersionKind MVKind)
Definition: SemaDecl.cpp:10590
clang::Sema::AMK_ProtocolImplementation
@ AMK_ProtocolImplementation
Merge availability attributes for an implementation of a protocol requirement.
Definition: Sema.h:3647
clang::ObjCContainerDecl
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:944
clang::ASTContext::addDeclaratorForUnnamedTagDecl
void addDeclaratorForUnnamedTagDecl(TagDecl *TD, DeclaratorDecl *DD)
Definition: ASTContext.cpp:11857
clang::DeclContextLookupResult
The results of name lookup within a DeclContext.
Definition: DeclBase.h:1300
clang::Token::isOneOf
bool isOneOf(tok::TokenKind K1, tok::TokenKind K2) const
Definition: Token.h:99
clang::DependentNameTypeLoc::setNameLoc
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:2348
clang::DeclaratorContext::KNRTypeList
@ KNRTypeList
clang::ASTContext::mergeObjCGCQualifiers
QualType mergeObjCGCQualifiers(QualType, QualType)
mergeObjCGCQualifiers - This routine merges ObjC's GC attribute of 'LHS' and 'RHS' attributes and ret...
Definition: ASTContext.cpp:10620
ValidKernelParam
@ ValidKernelParam
Definition: SemaDecl.cpp:8885
clang::DeclaratorDecl::getNumTemplateParameterLists
unsigned getNumTemplateParameterLists() const
Definition: Decl.h:815
clang::Sema::MergeSYCLDeviceHasAttr
SYCLDeviceHasAttr * MergeSYCLDeviceHasAttr(Decl *D, const SYCLDeviceHasAttr &A)
clang::Sema::CheckTypedefForVariablyModifiedType
void CheckTypedefForVariablyModifiedType(Scope *S, TypedefNameDecl *D)
Definition: SemaDecl.cpp:6398
clang::ImplicitCastExpr
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition: Expr.h:3676
clang::ArrayTypeLoc::getLBracketLoc
SourceLocation getLBracketLoc() const
Definition: TypeLoc.h:1521
clang::TU_Complete
@ TU_Complete
The translation unit is a complete translation unit.
Definition: LangOptions.h:759
isExternC
static bool isExternC(T *D)
Definition: SemaDecl.cpp:3310
clang::DeclSpec::TST_struct
static const TST TST_struct
Definition: DeclSpec.h:285
clang::Sema::mergeCodeSegAttr
CodeSegAttr * mergeCodeSegAttr(Decl *D, const AttributeCommonInfo &CI, StringRef Name)
clang::Sema::ParseTypedefDecl
TypedefDecl * ParseTypedefDecl(Scope *S, Declarator &D, QualType T, TypeSourceInfo *TInfo)
Subroutines of ActOnDeclarator().
Definition: SemaDecl.cpp:15481
clang::Sema::AlignPackInfo::getAlignMode
Mode getAlignMode() const
Definition: Sema.h:720
clang::Sema::handleTagNumbering
void handleTagNumbering(const TagDecl *Tag, Scope *TagScope)
Definition: SemaDecl.cpp:4586
clang::MemberExpr
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3220
clang::TypeLoc::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Get the full source range.
Definition: TypeLoc.h:152
clang::DeclSpec::TQ_restrict
@ TQ_restrict
Definition: DeclSpec.h:307
clang::CXXBasePaths
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Definition: CXXInheritance.h:117
clang::ASTContext::getTrivialTypeSourceInfo
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
Definition: ASTContext.cpp:2971
clang::CXXRecordDecl::hasNonTrivialDestructor
bool hasNonTrivialDestructor() const
Determine whether this class has a non-trivial destructor (C++ [class.dtor]p3)
Definition: DeclCXX.h:1331
clang::DeclaratorChunk::ParamInfo::IdentLoc
SourceLocation IdentLoc
Definition: DeclSpec.h:1253
clang::Builtin::Context::isScanfLike
bool isScanfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like scanf in its formatting rules and, if so, set the index to the...
Definition: Builtins.cpp:160
clang::InClassInitStyle
InClassInitStyle
In-class initialization styles for non-static data members.
Definition: Specifiers.h:256
clang::QualType::getTypePtr
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:6502
clang::RecordType::getDecl
RecordDecl * getDecl() const
Definition: Type.h:4659
clang::Attr::setImplicit
void setImplicit(bool I)
Definition: Attr.h:98
clang::NestedNameSpecifier::GlobalSpecifier
static NestedNameSpecifier * GlobalSpecifier(const ASTContext &Context)
Returns the nested name specifier representing the global scope.
Definition: NestedNameSpecifier.cpp:126
clang::Sema::DiagnoseUnusedParameters
void DiagnoseUnusedParameters(ArrayRef< ParmVarDecl * > Parameters)
Diagnose any unused parameters in the given sequence of ParmVarDecl pointers.
Definition: SemaDecl.cpp:14072
clang::ASTContext::getPointerType
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
Definition: ASTContext.cpp:3270
clang::DeclSpec::TQ_const
@ TQ_const
Definition: DeclSpec.h:306
clang::CPlusPlus11
@ CPlusPlus11
Definition: LangStandard.h:49
clang::ETK_Typename
@ ETK_Typename
The "typename" keyword precedes the qualified type name, e.g., typename T::type.
Definition: Type.h:5423
getCoreType
static QualType getCoreType(QualType Ty)
Definition: SemaDecl.cpp:5657
clang::CXXScopeSpec::MakeTrivial
void MakeTrivial(ASTContext &Context, NestedNameSpecifier *Qualifier, SourceRange R)
Make a new nested-name-specifier from incomplete source-location information.
Definition: DeclSpec.cpp:125
clang::NamedDecl::isCXXClassMember
bool isCXXClassMember() const
Determine whether this declaration is a C++ class member.
Definition: Decl.h:368
clang::Sema::ShouldWarnIfUnusedFileScopedDecl
bool ShouldWarnIfUnusedFileScopedDecl(const DeclaratorDecl *D) const
Definition: SemaDecl.cpp:1766
getDefinition
static const NamedDecl * getDefinition(const Decl *D)
Definition: SemaDecl.cpp:2835
clang::QualType::PrimitiveDefaultInitializeKind
PrimitiveDefaultInitializeKind
Definition: Type.h:1137
Parent
NodeId Parent
Definition: ASTDiff.cpp:192
clang::ReferenceType
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:2766
clang::CharUnits
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
clang::DeclSpec::getModulePrivateSpecLoc
SourceLocation getModulePrivateSpecLoc() const
Definition: DeclSpec.h:752
clang::PointerType::getPointeeType
QualType getPointeeType() const
Definition: Type.h:2665
clang::Sema::DiagnoseUnusedDecl
void DiagnoseUnusedDecl(const NamedDecl *ND)
DiagnoseUnusedDecl - Emit warnings about declarations that are not used unless they are marked attr(u...
Definition: SemaDecl.cpp:1975
clang::TypeLoc::initializeFullCopy
void initializeFullCopy(TypeLoc Other)
Initializes this by copying its information from another TypeLoc of the same type.
Definition: TypeLoc.h:202
clang::LookupResult::getSema
Sema & getSema() const
Get the Sema object that this lookup result is searching with.
Definition: Lookup.h:612
clang::Sema::CXXSpecialMember
CXXSpecialMember
Kinds of C++ special members.
Definition: Sema.h:1669
checkGlobalOrExternCConflict
static bool checkGlobalOrExternCConflict(Sema &S, const T *ND, bool IsGlobal, LookupResult &Previous)
Check for conflict between this global or extern "C" declaration and previous global or extern "C" de...
Definition: SemaDecl.cpp:8024
clang::Sema::CheckVariableDeclaration
bool CheckVariableDeclaration(VarDecl *NewVD, LookupResult &Previous)
Perform semantic checking on a newly-created variable declaration.
Definition: SemaDecl.cpp:8393
lookupUnqualifiedTypeNameInBase
static UnqualifiedTypeNameLookupResult lookupUnqualifiedTypeNameInBase(Sema &S, const IdentifierInfo &II, SourceLocation NameLoc, const CXXRecordDecl *RD)
Tries to perform unqualified lookup of the type decls in bases for dependent class.
Definition: SemaDecl.cpp:182
clang::Sema::mergeFormatAttr
FormatAttr * mergeFormatAttr(Decl *D, const AttributeCommonInfo &CI, IdentifierInfo *Format, int FormatIdx, int FirstArg)
clang::InheritedConstructor
Description of a constructor that was inherited from a base class.
Definition: DeclCXX.h:2395
clang::Decl::setInvalidDecl
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
clang::VarDecl::hasDependentAlignment
bool hasDependentAlignment() const
Determines if this variable's alignment is dependent.
Definition: Decl.cpp:2574
clang::Sema::CheckEnumConstant
EnumConstantDecl * CheckEnumConstant(EnumDecl *Enum, EnumConstantDecl *LastEnumConst, SourceLocation IdLoc, IdentifierInfo *Id, Expr *val)
Definition: SemaDecl.cpp:18059
SDK_Global
@ SDK_Global
Definition: SemaDecl.cpp:7769
clang::FunctionDecl::isFunctionTemplateSpecialization
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition: Decl.h:2693
clang::CXXConstructExpr::getArg
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition: ExprCXX.h:1611
clang::isTemplateInstantiation
bool isTemplateInstantiation(TemplateSpecializationKind Kind)
Determine whether this template specialization kind refers to an instantiation of an entity (as oppos...
Definition: Specifiers.h:197
clang::ASTContext::hasSameType
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2521
clang::DestructedTypeVisitor
Definition: NonTrivialTypeVisitor.h:21
clang::IndirectFieldDecl::Create
static IndirectFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, QualType T, llvm::MutableArrayRef< NamedDecl * > CH)
Definition: Decl.cpp:4998
clang::Sema::LookupOrdinaryName
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:4305
clang::Sema::MergeSYCLIntelNumSimdWorkItemsAttr
SYCLIntelNumSimdWorkItemsAttr * MergeSYCLIntelNumSimdWorkItemsAttr(Decl *D, const SYCLIntelNumSimdWorkItemsAttr &A)
clang::VarDecl::setStorageClass
void setStorageClass(StorageClass SC)
Definition: Decl.cpp:2063
clang::TypeLoc::castAs
T castAs() const
Convert to the specified TypeLoc type, asserting that this TypeLoc is of the desired type.
Definition: TypeLoc.h:77
clang::DeclSpec::TST_typeofExpr
static const TST TST_typeofExpr
Definition: DeclSpec.h:290
getMSManglingNumber
static unsigned getMSManglingNumber(const LangOptions &LO, Scope *S)
Definition: SemaDecl.cpp:4580
clang::Declarator::getEndLoc
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclSpec.h:1947
clang::Sema::BuildParmVarDeclForTypedef
ParmVarDecl * BuildParmVarDeclForTypedef(DeclContext *DC, SourceLocation Loc, QualType T)
Synthesizes a variable for a parameter arising from a typedef.
Definition: SemaDecl.cpp:14059
clang::NestedNameSpecifierLoc::getTypeLoc
TypeLoc getTypeLoc() const
For a nested-name-specifier that refers to a type, retrieve the type with source-location information...
Definition: NestedNameSpecifier.cpp:453
llvm::SmallVectorImpl
Definition: LLVM.h:39
clang::ASTContext::setObjCIdRedefinitionType
void setObjCIdRedefinitionType(QualType RedefType)
Set the user-written type that redefines id.
Definition: ASTContext.h:1838
clang::EnumDecl::isClosedFlag
bool isClosedFlag() const
Returns true if this enum is annotated with flag_enum and isn't annotated with enum_extensibility(ope...
Definition: Decl.cpp:4485
clang::sema::AnalysisBasedWarnings::Policy::disableCheckFallThrough
void disableCheckFallThrough()
Definition: AnalysisBasedWarnings.h:42
clang::Scope::DeclScope
@ DeclScope
This is a scope that can contain a declaration.
Definition: Scope.h:59
clang::CallExpr::arguments
arg_range arguments()
Definition: Expr.h:3092
clang::ASTContext::setucontext_tDecl
void setucontext_tDecl(TypeDecl *ucontext_tDecl)
Set the type for the C ucontext_t type.
Definition: ASTContext.h:1954
clang::FunctionDecl::isTemplateInstantiation
bool isTemplateInstantiation() const
Determines if the given function was instantiated from a function template.
Definition: Decl.cpp:3778
clang::Sema::HandleDeclarator
NamedDecl * HandleDeclarator(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParameterLists)
Definition: SemaDecl.cpp:5939
clang::InheritableParamAttr
Definition: Attr.h:180
clang::Builtin::Context::isPrintfLike
bool isPrintfLike(unsigned ID, unsigned &FormatIdx, bool &HasVAListArg)
Determine whether this builtin is like printf in its formatting rules and, if so, set the index to th...
Definition: Builtins.cpp:155
clang::Lexer::findLocationAfterToken
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition: Lexer.cpp:1293
clang::SC_None
@ SC_None
Definition: Specifiers.h:235
clang::ValueDecl::getType
QualType getType() const
Definition: Decl.h:686
checkDuplicateDefaultInit
static void checkDuplicateDefaultInit(Sema &S, CXXRecordDecl *Parent, SourceLocation DefaultInitLoc)
Definition: SemaDecl.cpp:5185
clang::Type::isFunctionReferenceType
bool isFunctionReferenceType() const
Definition: Type.h:6791
clang::DeducedType
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:5016
clang::FunctionDecl::getBuiltinID
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition: Decl.cpp:3342
clang::RecordDecl::setParamDestroyedInCallee
void setParamDestroyedInCallee(bool V)
Definition: Decl.h:4051
clang::VarTemplateDecl
Declaration of a variable template.
Definition: DeclTemplate.h:3079
clang::EvaluatedExprVisitor
EvaluatedExprVisitor - This class visits 'Expr *'s.
Definition: EvaluatedExprVisitor.h:128
clang::ASTContext::hasSameUnqualifiedType
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2545
clang::ASTContext::setStaticLocalNumber
void setStaticLocalNumber(const VarDecl *VD, unsigned Number)
Definition: ASTContext.cpp:11800
clang::GNUMode
@ GNUMode
Definition: LangStandard.h:55
clang::Sema::ParsingInitForAutoVars
llvm::SmallPtrSet< const Decl *, 4 > ParsingInitForAutoVars
ParsingInitForAutoVars - a set of declarations with auto types for which we are currently parsing the...
Definition: Sema.h:1028
clang::ArrayType::getElementType
QualType getElementType() const
Definition: Type.h:2919
Previous
StateNode * Previous
Definition: UnwrappedLineFormatter.cpp:1085
clang::ASTContext::getOverloadedTemplateName
TemplateName getOverloadedTemplateName(UnresolvedSetIterator Begin, UnresolvedSetIterator End) const
Retrieve the template name that corresponds to a non-empty lookup.
Definition: ASTContext.cpp:8962
clang::ParsedAttributes::getPool
AttributePool & getPool() const
Definition: ParsedAttr.h:1011
clang::ParsedAttributesView
Definition: ParsedAttr.h:909
clang::Expr
This represents one expression.
Definition: Expr.h:109
clang::FunctionType::getRegParmType
unsigned getRegParmType() const
Definition: Type.h:3827
clang::Sema::CheckFunctionOrTemplateParamDeclarator
void CheckFunctionOrTemplateParamDeclarator(Scope *S, Declarator &D)
Common checks for a parameter-declaration that should apply to both function parameters and non-type ...
Definition: SemaDecl.cpp:13913
clang::CXXScopeSpec::isEmpty
bool isEmpty() const
No scope specifier.
Definition: DeclSpec.h:190
clang::TargetInfo::shouldDLLImportComdatSymbols
virtual bool shouldDLLImportComdatSymbols() const
Does this target aim for semantic compatibility with Microsoft C++ code using dllimport/export attrib...
Definition: TargetInfo.h:1196
clang::FunctionDecl::getDescribedFunctionTemplate
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:3733
SM
#define SM(sm)
Definition: Cuda.cpp:81
clang::Sema::SkipBodyInfo::Previous
NamedDecl * Previous
Definition: Sema.h:2686
clang::IdentifierResolver::iterator
iterator - Iterate over the decls of a specified declaration name.
Definition: IdentifierResolver.h:69
clang::ParmVarDecl::Create
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition: Decl.cpp:2770
clang::Declarator::getAttributes
const ParsedAttributes & getAttributes() const
Definition: DeclSpec.h:2523
clang::ASTContext::getExternCContextDecl
ExternCContextDecl * getExternCContextDecl() const
Definition: ASTContext.cpp:1201
clang::UnqualifiedId::getSourceRange
SourceRange getSourceRange() const LLVM_READONLY
Return the source range that covers this unqualified-id.
Definition: DeclSpec.h:1159
clang::LabelDecl::isMSAsmLabel
bool isMSAsmLabel() const
Definition: Decl.h:529
clang::RecordDecl::Create
static RecordDecl * Create(const ASTContext &C, TagKind TK, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, RecordDecl *PrevDecl=nullptr)
Definition: Decl.cpp:4586
clang::RecordDecl::setNonTrivialToPrimitiveCopy
void setNonTrivialToPrimitiveCopy(bool V)
Definition: Decl.h:3996
clang::QualType::isDestructedType
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition: Type.h:1216
clang::VarDecl::hasLocalStorage
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1100
clang::CXXScopeSpec::getRange
SourceRange getRange() const
Definition: DeclSpec.h:69
clang::NestedNameSpecifier::getKind
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
Definition: NestedNameSpecifier.cpp:143
clang::sema::Capture::isVariableCapture
bool isVariableCapture() const
Definition: ScopeInfo.h:612
clang::Decl::dropAttrs
void dropAttrs()
Definition: DeclBase.cpp:878
OpenCLParamType
OpenCLParamType
Definition: SemaDecl.cpp:8884
clang::DeclSpec::SetRangeEnd
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:639
clang::MultiVersionKind
MultiVersionKind
Definition: Decl.h:1838
clang::TSK_ImplicitInstantiation
@ TSK_ImplicitInstantiation
This template specialization was implicitly instantiated from a template.
Definition: Specifiers.h:179
clang::Sema::canSkipFunctionBody
bool canSkipFunctionBody(Decl *D)
Determine whether we can skip parsing the body of a function definition, assuming we don't care about...
Definition: SemaDecl.cpp:14646
clang::QualType::PrimitiveCopyKind
PrimitiveCopyKind
Definition: Type.h:1163
clang::Decl::setLocalExternDecl
void setLocalExternDecl()
Changes the namespace of this declaration to reflect that it's a function-local extern declaration.
Definition: DeclBase.h:1082
clang::Sema::ActOnNameClassifiedAsNonType
ExprResult ActOnNameClassifiedAsNonType(Scope *S, const CXXScopeSpec &SS, NamedDecl *Found, SourceLocation NameLoc, const Token &NextToken)
Act on the result of classifying a name as a specific non-type declaration.
Definition: SemaDecl.cpp:1244
clang::Sema::PP
Preprocessor & PP
Definition: Sema.h:586
clang::EnumType
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:4675
clang::UnqualifiedIdKind::IK_ImplicitSelfParam
@ IK_ImplicitSelfParam
An implicit 'self' parameter.
clang::DeclContext::isFunctionOrMethod
bool isFunctionOrMethod() const
Definition: DeclBase.h:1924
clang::Builtin::Context::isNoThrow
bool isNoThrow(unsigned ID) const
Return true if we know this builtin never throws an exception.
Definition: Builtins.h:112
clang::CXXScopeSpec::getBeginLoc
SourceLocation getBeginLoc() const
Definition: DeclSpec.h:73
clang::FunctionProtoType::getExtProtoInfo
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:4121
clang::ASTContext::getObjCObjectPointerType
QualType getObjCObjectPointerType(QualType OIT) const
Return a ObjCObjectPointerType type for the given ObjCObjectType.
Definition: ASTContext.cpp:5491
clang::DeclSpec::getConstexprSpecLoc
SourceLocation getConstexprSpecLoc() const
Definition: DeclSpec.h:758
clang::DeclarationNameInfo::getLoc
SourceLocation getLoc() const
getLoc - Returns the main location of the declaration name.
Definition: DeclarationName.h:785
clang::EnumDecl::setPromotionType
void setPromotionType(QualType T)
Set the promotion type.
Definition: Decl.h:3767
clang::DeclarationNameInfo
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
Definition: DeclarationName.h:756
clang::Sema::MergeWorkGroupSizeHintAttr
WorkGroupSizeHintAttr * MergeWorkGroupSizeHintAttr(Decl *D, const WorkGroupSizeHintAttr &A)
clang::Type::isIncompleteType
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2235
clang::DeclSpec::TST_auto
static const TST TST_auto
Definition: DeclSpec.h:294
clang::ASTContext::getConstantArrayType
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArrayType::ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
Definition: ASTContext.cpp:3498
clang::Builtin::Context::isAuxBuiltinID
bool isAuxBuiltinID(unsigned ID) const
Return true if builtin ID belongs to AuxTarget.
Definition: Builtins.h:221
clang::ASTContext::DeclMustBeEmitted
bool DeclMustBeEmitted(const Decl *D)
Determines if the decl can be CodeGen'ed or deserialized from PCH lazily, only when used; this is onl...
Definition: ASTContext.cpp:11478
clang::NamedDecl::isReserved
ReservedIdentifierStatus isReserved(const LangOptions &LangOpts) const
Determine if the declaration obeys the reserved identifier rules of the given language.
Definition: Decl.cpp:1093
clang::FunctionDecl::parameters
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2487
clang::FunctionDecl::setBody
void setBody(Stmt *B)
Definition: Decl.cpp:3064
CommentDiagnostic.h
clang::AttributedType::getModifiedType
QualType getModifiedType() const
Definition: Type.h:4726
clang::Sema::ActOnPopScope
void ActOnPopScope(SourceLocation Loc, Scope *S)
Scope actions.
Definition: SemaDecl.cpp:2063
clang::TST_union
@ TST_union
Definition: Specifiers.h:77
clang::Decl::getLocation
SourceLocation getLocation() const
Definition: DeclBase.h:424
ExitFunctionBodyRAII::ExitFunctionBodyRAII
ExitFunctionBodyRAII(Sema &S, bool IsLambda)
Definition: SemaDecl.cpp:14682
clang::sema::CapturingScopeInfo::ReturnType
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:691
clang::FieldDecl::isAnonymousStructOrUnion
bool isAnonymousStructOrUnion() const
Determines whether this field is a representative for an anonymous struct or union.
Definition: Decl.cpp:4208
clang::Sema::mergeImportModuleAttr
WebAssemblyImportModuleAttr * mergeImportModuleAttr(Decl *D, const WebAssemblyImportModuleAttr &AL)
clang::TSCS_unspecified
@ TSCS_unspecified
Definition: Specifiers.h:221
clang::LangAS::opencl_generic
@ opencl_generic
clang::Sema::ActOnNameClassifiedAsOverloadSet
ExprResult ActOnNameClassifiedAsOverloadSet(Scope *S, Expr *OverloadSet)
Act on the result of classifying a name as an overload set.
Definition: SemaDecl.cpp:1261
clang::Decl::addAttr
void addAttr(Attr *A)
Definition: DeclBase.cpp:885
NonTrivialTypeVisitor.h
clang::DeclRefExpr
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1223
GCCTypeClass::None
@ None
SDK_StructuredBinding
@ SDK_StructuredBinding
Definition: SemaDecl.cpp:7774
clang::NamespaceDecl
Represent a C++ namespace.
Definition: Decl.h:541
clang::FunctionDecl
Represents a function declaration or definition.
Definition: Decl.h:1856
clang::Builtin::Context::isReturnsTwice
bool isReturnsTwice(unsigned ID) const
Return true if we know this builtin can return twice.
Definition: Builtins.h:122
clang::DeclaratorChunk::ParamInfo::Ident
IdentifierInfo * Ident
Definition: DeclSpec.h:1252
clang::RecordDecl
Represents a struct/union/class.
Definition: Decl.h:3885
clang::DeclContext::Equals
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:1996
clang::DeclarationNameTable::getCXXConstructorName
DeclarationName getCXXConstructorName(CanQualType Ty)
Returns the name of a C++ constructor for the given Type.
Definition: DeclarationName.cpp:310
clang::TypeWithKeyword::getTagTypeKindName
static StringRef getTagTypeKindName(TagTypeKind Kind)
Definition: Type.h:5465
clang::CallExpr
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2853
clang::DeclSpec::getBeginLoc
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: DeclSpec.h:507
clang::Sema::CheckRedeclarationModuleOwnership
bool CheckRedeclarationModuleOwnership(NamedDecl *New, NamedDecl *Old)
We've determined that New is a redeclaration of Old.
Definition: SemaDecl.cpp:1599
clang::FunctionType::ExtInfo::getProducesResult
bool getProducesResult() const
Definition: Type.h:3721
clang::diag::kind
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:62
clang::LookupResult::FoundUnresolvedValue
@ FoundUnresolvedValue
Name lookup found an unresolvable value declaration and cannot yet complete.
Definition: Lookup.h:68
clang::Sema::DelayedDiagnostics::add
void add(const sema::DelayedDiagnostic &diag)
Adds a delayed diagnostic.
Definition: DelayedDiagnostic.h:325
clang::FunctionDecl::getStorageClass
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:2584
clang::CXXOperatorCallExpr
A call to an overloaded operator written using operator syntax.
Definition: ExprCXX.h:82
clang::Sema::MergeSYCLIntelFPGAInitiationIntervalAttr
SYCLIntelFPGAInitiationIntervalAttr * MergeSYCLIntelFPGAInitiationIntervalAttr(Decl *D, const SYCLIntelFPGAInitiationIntervalAttr &A)
clang::Sema::ActOnStartOfFunctionDef
Decl * ActOnStartOfFunctionDef(Scope *S, Declarator &D, MultiTemplateParamsArg TemplateParamLists, SkipBodyInfo *SkipBody=nullptr)
Definition: SemaDecl.cpp:14239
StmtCXX.h
clang::Sema::MergeSYCLIntelESimdVectorizeAttr
SYCLIntelESimdVectorizeAttr * MergeSYCLIntelESimdVectorizeAttr(Decl *D, const SYCLIntelESimdVectorizeAttr &A)
clang::CXXConversionDecl::Create
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2771
clang::TypoCorrection::end
decl_iterator end()
Definition: TypoCorrection.h:236
clang::FunctionDecl::setIsMultiVersion
void setIsMultiVersion(bool V=true)
Sets the multiversion state for this declaration and all of its redeclarations.
Definition: Decl.h:2441
clang::LookupResult::getLookupNameInfo
const DeclarationNameInfo & getLookupNameInfo() const
Gets the name info to look up.
Definition: Lookup.h:233
clang::DeclarationNameTable::getCXXLiteralOperatorName
DeclarationName getCXXLiteralOperatorName(IdentifierInfo *II)
Get the name of the literal operator function with II as the identifier.
Definition: DeclarationName.cpp:374
clang::CXXConstructExpr
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1460
clang::Decl::setLocalOwningModule
void setLocalOwningModule(Module *M)
Definition: DeclBase.h:768
clang::FunctionDecl::isDefined
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition: Decl.cpp:3019
clang::Sema::RebuildTypeInCurrentInstantiation
TypeSourceInfo * RebuildTypeInCurrentInstantiation(TypeSourceInfo *T, SourceLocation Loc, DeclarationName Name)
Rebuilds a type within the context of the current instantiation.
Definition: SemaTemplate.cpp:10822
clang::NamedDecl::declarationReplaces
bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer=true) const
Determine whether this declaration, if known to be well-formed within its context,...
Definition: Decl.cpp:1768
clang::ActionResult::isUsable
bool isUsable() const
Definition: Ownership.h:166
clang::ASTContext::GetBuiltinTypeError
GetBuiltinTypeError
Definition: ASTContext.h:2193
clang::StringLiteral::getString
StringRef getString() const
Definition: Expr.h:1850
clang::IdentifierInfo::isEditorPlaceholder
bool isEditorPlaceholder() const
Return true if this identifier is an editor placeholder.
Definition: IdentifierTable.h:453
clang::ASTContext::getLangOpts
const LangOptions & getLangOpts() const
Definition: ASTContext.h:782
clang::UnqualifiedId::getKind
UnqualifiedIdKind getKind() const
Determine what kind of name we have.
Definition: DeclSpec.h:1032
clang::TargetInfo::getIntWidth
unsigned getIntWidth() const
getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for this target,...
Definition: TargetInfo.h:454
clang::FunctionDecl::getInstantiatedFromMemberFunction
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:3705
clang::CharUnits::getQuantity
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition: CharUnits.h:179
clang::CXXScopeSpec::isNotEmpty
bool isNotEmpty() const
A scope specifier is present, but may be valid or invalid.
Definition: DeclSpec.h:192
clang::LookupResult::getRepresentativeDecl
NamedDecl * getRepresentativeDecl() const
Fetches a representative decl. Useful for lazy diagnostics.
Definition: Lookup.h:524
clang::DeclSpec::SetTypeSpecType
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:824
clang::DeclSpec::getAtomicSpecLoc
SourceLocation getAtomicSpecLoc() const
Definition: DeclSpec.h:551
clang::DeclaratorDecl::getTypeSourceInfo
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:756
clang::FixItHint::CreateReplacement
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition: Diagnostic.h:134
clang::ClassScopeFunctionSpecializationDecl::Create
static ClassScopeFunctionSpecializationDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation Loc, CXXMethodDecl *FD, bool HasExplicitTemplateArgs, const TemplateArgumentListInfo &TemplateArgs)
Definition: DeclTemplate.h:2630
clang::ICIS_NoInit
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:257
clang::ParenType
Sugar for parentheses used when specifying types.
Definition: Type.h:2629
clang::CXXConstructExpr::isElidable
bool isElidable() const
Whether this construction is elidable.
Definition: ExprCXX.h:1538
clang::Type::isIntegralOrEnumerationType
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:7160
clang::Sema::ActOnParamDeclarator
Decl * ActOnParamDeclarator(Scope *S, Declarator &D)
ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator() to introduce parameters into fun...
Definition: SemaDecl.cpp:13952
clang::DeclSpec
Captures information about "declaration specifiers".
Definition: DeclSpec.h:229
clang::CXXMethodDecl::isVirtual
bool isVirtual() const
Definition: DeclCXX.h:2012
clang::DeclSpec::getTypeSpecScope
CXXScopeSpec & getTypeSpecScope()
Definition: DeclSpec.h:503
clang::Declarator::isRedeclaration
bool isRedeclaration() const
Definition: DeclSpec.h:2602
clang::DeclSpec::SCS_extern
@ SCS_extern
Definition: DeclSpec.h:236
clang::Sema::DeviceDiagnosticReason::Sycl
@ Sycl
SYCL specific diagnostic.
clang::Sema::AdjustDestructorExceptionSpec
void AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor)
Build an exception spec for destructors that don't have one.
Definition: SemaDeclCXX.cpp:13866
clang::Sema::MergeSYCLAddIRAttributesGlobalVariableAttr
SYCLAddIRAttributesGlobalVariableAttr * MergeSYCLAddIRAttributesGlobalVariableAttr(Decl *D, const SYCLAddIRAttributesGlobalVariableAttr &A)
clang::DeclSpec::TSCS_thread_local
static const TSCS TSCS_thread_local
Definition: DeclSpec.h:249
clang::ReturnStmt
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:2765
ExitFunctionBodyRAII::~ExitFunctionBodyRAII
~ExitFunctionBodyRAII()
Definition: SemaDecl.cpp:14683
clang::DeclSpec::getRepAsType
ParsedType getRepAsType() const
Definition: DeclSpec.h:486
clang::Sema::MergeSYCLIntelLoopFuseAttr
SYCLIntelLoopFuseAttr * MergeSYCLIntelLoopFuseAttr(Decl *D, const SYCLIntelLoopFuseAttr &A)
clang::Sema::deduceVarTypeFromInitializer
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:11925
clang::Decl::getMostRecentDecl
Decl * getMostRecentDecl()
Retrieve the most recent declaration that declares the same entity as this declaration (which may be ...
Definition: DeclBase.h:1007
clang::NestedNameSpecifierLocBuilder::getWithLocInContext
NestedNameSpecifierLoc getWithLocInContext(ASTContext &Context) const
Retrieve a nested-name-specifier with location information, copied into the given AST context.
Definition: NestedNameSpecifier.cpp:692
clang::declaresSameEntity
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1206
clang::VarDecl::CallInit
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:883
clang::TypeSourceInfo::getTypeLoc
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:244
clang::UnqualifiedIdKind::IK_ConstructorTemplateId
@ IK_ConstructorTemplateId
A constructor named via a template-id.
clang::ValueDecl::setType
void setType(QualType newType)
Definition: Decl.h:687
ParsedTemplate.h
clang::ObjCInterfaceDecl::getDefinition
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1527
clang::Builtin::Context::isPredefinedLibFunction
bool isPredefinedLibFunction(unsigned ID) const
Determines whether this builtin is a predefined libc/libm function, such as "malloc",...
Definition: Builtins.h:141
clang::CXXRecordDecl::setDescribedClassTemplate
void setDescribedClassTemplate(ClassTemplateDecl *Template)
Definition: DeclCXX.cpp:1814
clang::getAsTypeTemplateDecl
TemplateDecl * getAsTypeTemplateDecl(Decl *D)
Definition: DeclTemplate.h:3353
ShouldDiagnoseUnusedDecl
static bool ShouldDiagnoseUnusedDecl(const NamedDecl *D)
Definition: SemaDecl.cpp:1849
Initialization.h
clang::Sema::ParsedFreeStandingDeclSpec
Decl * ParsedFreeStandingDeclSpec(Scope *S, AccessSpecifier AS, DeclSpec &DS, RecordDecl *&AnonRecord)
ParsedFreeStandingDeclSpec - This method is invoked when a declspec with no declarator (e....
Definition: SemaDecl.cpp:4568
clang::ASTContext::addTypedefNameForUnnamedTagDecl
void addTypedefNameForUnnamedTagDecl(TagDecl *TD, TypedefNameDecl *TND)
Definition: ASTContext.cpp:11847
clang::FileScopeAsmDecl::Create
static FileScopeAsmDecl * Create(ASTContext &C, DeclContext *DC, StringLiteral *Str, SourceLocation AsmLoc, SourceLocation RParenLoc)
Definition: Decl.cpp:5099
clang::CXXMethodDecl::getParent
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2083
clang::CXXMethodDecl
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:1968
clang::CXXScopeSpec::isInvalid
bool isInvalid() const
An error occurred during parsing of the scope specifier.
Definition: DeclSpec.h:195
clang::driver::types::getTypeName
const char * getTypeName(ID Id)
getTypeName - Return the name of the type for Id.
Definition: Types.cpp:52
clang::NamedDecl::setModulePrivate
void setModulePrivate()
Specify that this declaration was marked as being private to the module in which it was defined.
Definition: DeclBase.h:634
clang::Type::isUndeducedType
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:7179
clang::Declarator::getMutableDeclSpec
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:1917
clang::ObjCIvarDecl::Package
@ Package
Definition: DeclObjC.h:1928
clang::Sema::ActOnFinishInlineFunctionDef
void ActOnFinishInlineFunctionDef(FunctionDecl *D)
Definition: SemaDecl.cpp:14268
clang::LookupResult::isAmbiguous
bool isAmbiguous() const
Definition: Lookup.h:301
clang::TypeSpecifierType
TypeSpecifierType
Specifies the kind of type.
Definition: Specifiers.h:52
clang::ConstexprSpecKind::Unspecified
@ Unspecified
clang::Decl::getDeclContext
DeclContext * getDeclContext()
Definition: DeclBase.h:433
clang::FunctionDecl::isOutOfLine
bool isOutOfLine() const override
Determine whether this is or was instantiated from an out-of-line definition of a member function.
Definition: Decl.cpp:4026
clang::SourceManager::getSpellingLoc
SourceLocation getSpellingLoc(SourceLocation Loc) const
Given a SourceLocation object, return the spelling location referenced by the ID.
Definition: SourceManager.h:1206
clang::VarDecl::DefinitionKind
DefinitionKind
Definition: Decl.h:1209
clang::StorageClass
StorageClass
Storage classes.
Definition: Specifiers.h:233
clang::NamedDecl::getName
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition: Decl.h:274
clang::DeclSpec::getThreadStorageClassSpec
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:441
clang::LocalInstantiationScope::InstantiatedLocal
void InstantiatedLocal(const Decl *D, Decl *Inst)
Definition: SemaTemplateInstantiate.cpp:3705